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 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.
- Tree Traversals (Inorder, Preorder and Postorder)
- Find the node with minimum value in a Binary Search Tree
- Write a program to Calculate Size of a tree | Recursion
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Delete a Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Convert a Binary Tree into its Mirror Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Lowest Common Ancestor in a Binary Search Tree.
- The Great Tree-List Recursion Problem.
- Check sum of Covered and Uncovered nodes of Binary Tree
- Level Order Tree Traversal
- Program to count leaf nodes in a binary tree
- A program to check if a binary tree is BST or not
- Check for Children Sum Property in a Binary Tree