Open In App
Related Articles

Find right sibling of a binary tree with parent pointers

Improve Article
Improve
Save Article
Save
Like Article
Like

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:

C++




// C program to print right sibling of a node
#include <bits/stdc++.h>
 
// A Binary Tree Node
struct Node {
    int data;
    Node *left, *right, *parent;
};
 
// A utility function to create a new Binary
// Tree Node
Node* newNode(int item, Node* parent)
{
    Node* temp = new Node;
    temp->data = item;
    temp->left = temp->right = NULL;
    temp->parent = parent;
    return temp;
}
 
// Method to find right sibling
Node* findRightSibling(Node* node, int level)
{
    if (node == NULL || node->parent == NULL)
        return NULL;
 
    // 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
           || (node->parent->right == NULL
               && node->parent->left == node)) {
        if (node->parent == NULL
            || node->parent->parent == NULL)
            return NULL;
 
        node = node->parent;
        level--;
    }
 
    // Move to the required child, where right sibling
    // can be present
    node = node->parent->right;
 
    if (node == NULL)
        return NULL;
    // find right sibling in the given subtree(from current
    // node), when level will be 0
    while (level < 0) {
 
        // Iterate through subtree
        if (node->left != NULL)
            node = node->left;
        else if (node->right != NULL)
            node = node->right;
        else
 
            // if no child are there, we cannot have right
            // sibling in this path
            break;
 
        level++;
    }
 
    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 Program to test above functions
int main()
{
    Node* root = newNode(1, NULL);
    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
    Node* res = findRightSibling(root->left->left->left->left, 0);
    if (res == NULL)
        printf("No right sibling");
    else
        printf("%d", res->data);
 
    return 0;
}


Java




// Java program to print right sibling of a node
public class Right_Sibling {
 
    // A Binary Tree Node
    static class Node {
        int data;
        Node left, right, parent;
 
        // Constructor
        public Node(int data, Node parent)
        {
            this.data = data;
            left = null;
            right = null;
            this.parent = parent;
        }
    };
 
    // Method to find right sibling
    static Node findRightSibling(Node node, int level)
    {
        if (node == null || node.parent == null)
            return null;
 
        // 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
               || (node.parent.right == null
                   && node.parent.left == node)) {
            if (node.parent == null)
                return null;
 
            node = node.parent;
            level--;
        }
 
        // 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 != null)
                node = node.left;
            else if (node.right != null)
                node = node.right;
            else
 
                // if no child are there, we cannot have right
                // sibling in this path
                break;
 
            level++;
        }
 
        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 Program to test above functions
    public static void main(String args[])
    {
        Node root = new Node(1, null);
        root.left = new Node(2, root);
        root.right = new Node(3, root);
        root.left.left = new Node(4, root.left);
        root.left.right = new Node(6, root.left);
        root.left.left.left = new Node(7, root.left.left);
        root.left.left.left.left = new Node(10, root.left.left.left);
        root.left.right.right = new Node(9, root.left.right);
        root.right.right = new Node(5, root.right);
        root.right.right.right = new Node(8, root.right.right);
        root.right.right.right.right = new Node(12, root.right.right.right);
 
        // passing 10
        System.out.println(findRightSibling(root.left.left.left.left, 0).data);
    }
}
// This code is contributed by Sumit Ghosh


Python3




# Python3 program to print right sibling
# of a node
 
# A class to create a new Binary
# Tree Node
class newNode:
    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):
        return 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):
            return 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
        else if (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


C#




using System;
 
// C# program to print right sibling of a node
public class Right_Sibling {
 
    // A Binary Tree Node
    public class Node {
        public int data;
        public Node left, right, parent;
 
        // Constructor
        public Node(int data, Node parent)
        {
            this.data = data;
            left = null;
            right = null;
            this.parent = parent;
        }
    }
 
    // Method to find right sibling
    public static Node findRightSibling(Node node, int level)
    {
        if (node == null || node.parent == null) {
            return null;
        }
 
        // 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
               || (node.parent.right == null
                   && node.parent.left == node)) {
            if (node.parent == null
                || node.parent.parent == null) {
                return null;
            }
 
            node = node.parent;
            level--;
        }
 
        // 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 != null) {
                node = node.left;
            }
            else if (node.right != null) {
                node = node.right;
            }
            else {
 
                // if no child are there, we cannot have right
                // sibling in this path
                break;
            }
 
            level++;
        }
 
        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 Program to test above functions
    public static void Main(string[] args)
    {
        Node root = new Node(1, null);
        root.left = new Node(2, root);
        root.right = new Node(3, root);
        root.left.left = new Node(4, root.left);
        root.left.right = new Node(6, root.left);
        root.left.left.left = new Node(7, root.left.left);
        root.left.left.left.left = new Node(10, root.left.left.left);
        root.left.right.right = new Node(9, root.left.right);
        root.right.right = new Node(5, root.right);
        root.right.right.right = new Node(8, root.right.right);
        root.right.right.right.right = new Node(12, root.right.right.right);
 
        // passing 10
        Console.WriteLine(findRightSibling(root.left.left.left.left, 0).data);
    }
}
 
// This code is contributed by Shrikant13


Javascript




<script>
    // Javascript program to print right sibling of a node
     
    // A Binary Tree Node
    class Node
    {
        constructor(data, parent) {
           this.left = null;
           this.right = null;
           this.data = data;
           this.parent = parent;
        }
    }
     
    // Method to find right sibling
    function findRightSibling(node, level)
    {
        if (node == null || node.parent == null)
            return null;
  
        // 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
               || (node.parent.right == null
                   && node.parent.left == node)) {
            if (node.parent == null)
                return null;
  
            node = node.parent;
            level--;
        }
  
        // 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 != null)
                node = node.left;
            else if (node.right != null)
                node = node.right;
            else
  
                // if no child are there, we cannot have right
                // sibling in this path
                break;
  
            level++;
        }
  
        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);
    }
     
    let root = new Node(1, null);
    root.left = new Node(2, root);
    root.right = new Node(3, root);
    root.left.left = new Node(4, root.left);
    root.left.right = new Node(6, root.left);
    root.left.left.left = new Node(7, root.left.left);
    root.left.left.left.left = new Node(10, root.left.left.left);
    root.left.right.right = new Node(9, root.left.right);
    root.right.right = new Node(5, root.right);
    root.right.right.right = new Node(8, root.right.right);
    root.right.right.right.right = new Node(12, root.right.right.right);
 
    // passing 10
    document.write(findRightSibling(root.left.left.left.left, 0).data);
    
   // This code is contributed by divyesh072019.
</script>


Output

12

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

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 15 Jul, 2022
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials