Open In App

Find right sibling of a binary tree with parent pointers

Given a binary tree with parent pointers, find the right sibling of a given node(pointer to the node will be given), if it doesn’t exist return null. Do it in O(1) space and O(n) time?

Examples: 



             1
            / \
           2   3
          /  \  \
         4    6  5
        /      \  \
       7        9  8
       /         \
      10         12
Input : Given above tree with parent pointer and node 10
Output : 12 

Approach: The idea is to find out the first right child of the nearest ancestor which is neither the current node nor the parent of the current node, keep track of the level in those while going up. then, iterate through that node first left child, if the left is not there then, right child and if the level becomes 0, then, this is the next right sibling of the given node.
In the above case, if the given node is 7, we will end up with 6 to find the right child which doesn’t have any child.

In this case, we need to recursively call for the right sibling with the current level, so that we case reach 8. 



Implementation:





















Output
12

Time Complexity: O(N)
Auxiliary Space: O(1)


Article Tags :