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.
# Python3 program to print right sibling
# of a node
# A class to create a new Binary
# Tree Node
def __init__(self, item, parent):
self.data = item
self.left = self.right = None
self.parent = parent
# Method to find right sibling
def findRightSibling(node, level):
if (node == None or node.parent == None):
# GET Parent pointer whose right child is not
# a parent or itself of this node. There might
# be case when parent has no right child, but,
# current node is left child of the parent
# (second condition is for that).
while (node.parent.right == node or
(node.parent.right == None and
node.parent.left == node)):
if (node.parent == None):
node = node.parent
level -= 1
# Move to the required child, where
# right sibling can be present
node = node.parent.right
# find right sibling in the given subtree
# (from current node), when level will be 0
while (level < 0): # Iterate through subtree if (node.left != None): node = node.left elif (node.right != None): node = node.right else: # if no child are there, we cannot # have right sibling in this path break level += 1 if (level == 0): return node # This is the case when we reach 9 node # in the tree, where we need to again # recursively find the right sibling return findRightSibling(node, level) # Driver Code if __name__ == '__main__': root = newNode(1, None) root.left = newNode(2, root) root.right = newNode(3, root) root.left.left = newNode(4, root.left) root.left.right = newNode(6, root.left) root.left.left.left = newNode(7, root.left.left) root.left.left.left.left = newNode(10, root.left.left.left) root.left.right.right = newNode(9, root.left.right) root.right.right = newNode(5, root.right) root.right.right.right = newNode(8, root.right.right) root.right.right.right.right = newNode(12, root.right.right.right) # passing 10 res = findRightSibling(root.left.left.left.left, 0) if (res == None): print("No right sibling") else: print(res.data) # This code is contributed by PranchalK [tabby title="C#"]
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.