Preorder Successor of a Node in Binary Tree
Given a binary tree and a node in the binary tree, find the preorder successor of the given node. It may be assumed that every node has a parent link.
Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Input : 4 Output : 18 Preorder traversal of given tree is 20, 10, 4, 18, 14, 13, 15, 19, 26, 24, 27. Input : 19 Output : 26
A simple solution is to first store the Preorder 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), as we will traverse the tree for searching the node.
Auxiliary Space: O(n), as we need extra space for storing the elements of the tree.
An efficient solution is based on the below observations.
- If the left child of a given node exists, then the left child is the preorder successor.
- If the left child does not exist, however, the right child exists, then the preorder successor is the right child.
- If the left child and the right child does not exist and given node is the left child of its parent, then its sibling is its preorder successor.
- If none of the above conditions are satisfied (left child does not exist and given node is not left child of its parent), then we move up using parent pointers until one of the following happens.
- We reach the root. In this case, a preorder successor does not exist.
- The current node (one of the ancestors of the given node) is the left child of its parent, in this case, the preorder successor is a sibling of the current node.
Preorder successor of 19 is 26
Time Complexity: O(h) where h is the height of the given Binary Tree, as we are not traversing all nodes. We have checked the child of each node that is equivalent to traversing the height of the tree.
Auxiliary Space: O(1), as we are not using any extra space.