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
Idea is to find out first right child of nearest ancestor which is neither the current node nor parent of current node, keep track of level in those while going up. then, iterate through that node first left child, if left is not there then, right child and if level becomes 0, then, this is the next right sibling of the given node.
In above case if given node is 7, we will end up with 6 to find right child which doesn’t have any child.
In this case we need to recursively call for right sibling with the current level, so that we case reach 8.
This article is contributed by Krishna Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Find the parent of a node in the given binary tree
- Find parent of given node in a Binary Tree with given postorder traversal
- Find Height of Binary Tree represented by Parent array
- Sum of all parent-child differences in a Binary Tree
- Maximum parent children sum in Binary tree
- Clone a Binary Tree with Random Pointers
- Sum of all the child nodes with even parent values in a Binary Tree
- Construct Binary Tree from given Parent Array representation
- Modify a binary tree to get preorder traversal using right pointers only
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
- Find parent of each node in a tree for multiple queries
- Right sibling of each node in a tree given as array of edges
- Left-Child Right-Sibling Representation of Tree
- Creating a tree with Left-Child Right-Sibling Representation
- Height of n-ary tree if parent array is given
- Find LCA in Binary Tree using RMQ
- Height of a generic tree from parent array
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree