Given a binary tree and a node in the binary tree, find the Postorder predecessor of the given node.
Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Input : 4 Output : 10 Postorder traversal of given tree is 4, 13, 15, 14, 19, 18, 10, 24, 27, 26, 20. Input : 24 Output : 10
A simple solution is to first store the Postorder traversal of the given tree in an array then linearly search the given node and print the node next to it.
Time Complexity : O(n)
Auxiliary Space : O(n)
An efficient solution is based on the below observations.
- If the right child of a given node exists, then the right child is the postorder predecessor.
- If the right child does not exist and the given node is left child of its parent, then its sibling is its Postorder predecessor.
- If none of the above conditions are satisfied (left child does not exist and given node is not the right child of its parent), then we move up using parent pointers until one of the following happens.
- We reach the root. In this case, the Postorder predecessor does not exist.
- The current node (one of the ancestors of the given node) is the right child of its parent, in this case, the postorder predecessor is the sibling of the current node.
Postorder predecessor of 18 is 19
Time Complexity: O(h) where h is the height of given Binary Tree
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes