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?
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.
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.
Time Complexity: O(N)
Auxiliary Space: O(1)
This article is contributed by Krishna Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.