Open In App

Creating a tree with Left-Child Right-Sibling Representation

Last Updated : 01 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Left-Child Right-Sibling Representation is a different representation of an n-ary tree where instead of holding a reference to each and every child node, a node holds just two references, first a reference to its first child, and the other to its immediate next sibling. This new transformation not only removes the need for advanced knowledge of the number of children a node has but also limits the number of references to a maximum of two, thereby making it so much easier to code. 

At each node, link children of same parent from left to right.
Parent should be linked with only first child.

Examples: 

Left Child Right Sibling tree representation
      10
      |  
      2 -> 3 -> 4 -> 5
      |    |  
      6    7 -> 8 -> 9

Prerequisite: Left-Child Right-Sibling Representation of Tree 

Below is the implementation. 

C++




// C++ program to create a tree with left child
// right sibling representation.
#include<bits/stdc++.h>
using namespace std;
 
struct Node
{
    int data;
    struct Node *next;
    struct Node *child;
};
 
// Creating new Node
Node* newNode(int data)
{
    Node *newNode = new Node;
    newNode->next = newNode->child = NULL;
    newNode->data = data;
    return newNode;
}
 
// Adds a sibling to a list with starting with n
Node *addSibling(Node *n, int data)
{
    if (n == NULL)
        return NULL;
 
    while (n->next)
        n = n->next;
 
    return (n->next = newNode(data));
}
 
// Add child Node to a Node
Node *addChild(Node * n, int data)
{
    if (n == NULL)
        return NULL;
 
    // Check if child list is not empty.
    if (n->child)
        return addSibling(n->child, data);
    else
        return (n->child = newNode(data));
}
 
// Traverses tree in depth first order
void traverseTree(Node * root)
{
    if (root == NULL)
        return;
 
    while (root)
    {
        cout << " " << root->data;
        if (root->child)
            traverseTree(root->child);
        root = root->next;
    }
}
 
//Driver code
 
int main()
{
    /*   Let us create below tree
    *           10
    *     /   /    \   \
    *    2  3      4   5
    *              |   /  | \
    *              6   7  8  9   */
 
    // Left child right sibling
    /*  10
    *    |
    *    2 -> 3 -> 4 -> 5
    *              |    |
    *              6    7 -> 8 -> 9  */
    Node *root = newNode(10);
    Node *n1  = addChild(root, 2);
    Node *n2  = addChild(root, 3);
    Node *n3  = addChild(root, 4);
    Node *n4  = addChild(n3, 6);
    Node *n5  = addChild(root, 5);
    Node *n6  = addChild(n5, 7);
    Node *n7  = addChild(n5, 8);
    Node *n8  = addChild(n5, 9);
    traverseTree(root);
    return 0;
}


Java




// Java program to create a tree with left child
// right sibling representation.
 
class GFG {
     
    static class NodeTemp
    {
        int data;
        NodeTemp next, child;
        public NodeTemp(int data)
        {
            this.data = data;
            next = child = null;
        }
    }
     
    // Adds a sibling to a list with starting with n
    static public NodeTemp addSibling(NodeTemp node, int data)
    {
        if(node == null)
            return null;
        while(node.next != null)
            node = node.next;
        return(node.next = new NodeTemp(data));
    }
         
    // Add child Node to a Node
    static public NodeTemp addChild(NodeTemp node,int data)
    {
        if(node == null)
            return null;
     
        // Check if child is not empty.
        if(node.child != null)
            return(addSibling(node.child,data));
        else
            return(node.child = new NodeTemp(data));
    }
 
    // Traverses tree in depth first order
    static public void traverseTree(NodeTemp root)
    {
        if(root == null)
            return;
        while(root != null)
        {
            System.out.print(root.data + " ");
            if(root.child != null)
                traverseTree(root.child);
            root = root.next;
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
         
        /*   Let us create below tree
        *           10
        *     /   /    \   \
        *    2  3      4   5
        *              |   /  | \
        *              6   7  8  9   */
      
        // Left child right sibling
        /*  10
        *    |
        *    2 -> 3 -> 4 -> 5
        *              |    |
        *              6    7 -> 8 -> 9  */
 
        NodeTemp root = new NodeTemp(10);
        NodeTemp n1 = addChild(root,2);
        NodeTemp n2 = addChild(root,3);
        NodeTemp n3 = addChild(root,4);
        NodeTemp n4 = addChild(n3,6);
        NodeTemp n5 = addChild(root,5);
        NodeTemp n6 = addChild(n5,7);
        NodeTemp n7 = addChild(n5,8);
        NodeTemp n8 = addChild(n5,9);
         
        traverseTree(root);
    }
}
 
// This code is contributed by M.V.S.Surya Teja.


Python3




# Python3 program to create a tree with
# left child right sibling representation.
 
# Creating new Node
class newNode:
    def __init__(self, data):
        self.Next = self.child = None
        self.data = data
 
# Adds a sibling to a list with
# starting with n
def addSibling(n, data):
    if (n == None):
        return None
 
    while (n.Next):
        n = n.Next
    n.Next = newNode(data)
    return n.Next
 
# Add child Node to a Node
def addChild(n, data):
    if (n == None):
        return None
 
    # Check if child list is not empty.
    if (n.child):
        return addSibling(n.child, data)
    else:
        n.child = newNode(data)
        return n.child
 
# Traverses tree in depth first order
def traverseTree(root):
    if (root == None):
        return
 
    while (root):
        print(root.data, end = " ")
        if (root.child):
            traverseTree(root.child)
        root = root.Next
 
# Driver code
if __name__ == '__main__':
     
    # Let us create below tree
    #         10
    #     / / \ \
    # 2 3     4 5
    #             | / | \
    #             6 7 8 9
 
    # Left child right sibling
    # 10
    # |
    # 2 -> 3 -> 4 -> 5
    #             | |
    #             6 7 -> 8 -> 9
    root = newNode(10)
    n1 = addChild(root, 2)
    n2 = addChild(root, 3)
    n3 = addChild(root, 4)
    n4 = addChild(n3, 6)
    n5 = addChild(root, 5)
    n6 = addChild(n5, 7)
    n7 = addChild(n5, 8)
    n8 = addChild(n5, 9)
    traverseTree(root)
     
# This code is contributed by pranchalK


C#




// C# program to create a tree with left
// child right sibling representation.
using System;
 
class GFG
{
public class NodeTemp
{
    public int data;
    public NodeTemp next, child;
    public NodeTemp(int data)
    {
        this.data = data;
        next = child = null;
    }
}
 
// Adds a sibling to a list with
// starting with n
public static NodeTemp addSibling(NodeTemp node,
                                  int data)
{
    if (node == null)
    {
        return null;
    }
    while (node.next != null)
    {
        node = node.next;
    }
    return (node.next = new NodeTemp(data));
}
 
// Add child Node to a Node
public static NodeTemp addChild(NodeTemp node,
                                int data)
{
    if (node == null)
    {
        return null;
    }
 
    // Check if child is not empty.
    if (node.child != null)
    {
        return (addSibling(node.child,data));
    }
    else
    {
        return (node.child = new NodeTemp(data));
    }
}
 
// Traverses tree in depth first order
public static void traverseTree(NodeTemp root)
{
    if (root == null)
    {
        return;
    }
    while (root != null)
    {
        Console.Write(root.data + " ");
        if (root.child != null)
        {
            traverseTree(root.child);
        }
        root = root.next;
    }
}
 
// Driver code
public static void Main(string[] args)
{
 
    /* Let us create below tree
    *         10
    *     / / \ \
    * 2 3     4 5
    *             | / | \
    *             6 7 8 9 */
 
    // Left child right sibling
    /* 10
    * |
    * 2 -> 3 -> 4 -> 5
    *             | |
    *             6 7 -> 8 -> 9 */
 
    NodeTemp root = new NodeTemp(10);
    NodeTemp n1 = addChild(root, 2);
    NodeTemp n2 = addChild(root, 3);
    NodeTemp n3 = addChild(root, 4);
    NodeTemp n4 = addChild(n3, 6);
    NodeTemp n5 = addChild(root, 5);
    NodeTemp n6 = addChild(n5, 7);
    NodeTemp n7 = addChild(n5, 8);
    NodeTemp n8 = addChild(n5, 9);
 
    traverseTree(root);
}
}
 
// This code is contributed by Shrikant13


Javascript




<script>
 
// Javascript program to create a tree with left child
// right sibling representation.
     
    class NodeTemp
    {
        constructor(data)
        {
            this.data=data;
            this.next = this.child = null;
        }
    }
     
    // Adds a sibling to a list with starting with n
    function addSibling(node,data)
    {
        if(node == null)
            return null;
        while(node.next != null)
            node = node.next;
        return(node.next = new NodeTemp(data));
    }
     
    // Add child Node to a Node
    function addChild(node,data)
    {
        if(node == null)
            return null;
      
        // Check if child is not empty.
        if(node.child != null)
            return(addSibling(node.child,data));
        else
            return(node.child = new NodeTemp(data));
             
    }
     
    // Traverses tree in depth first order
    function traverseTree(root)
    {
        if(root == null)
            return;
        while(root != null)
        {
            document.write(root.data + " ");
            if(root.child != null)
                traverseTree(root.child);
            root = root.next;
        }
    }
     
    // Driver code
     
    /*   Let us create below tree
        *           10
        *     /   /    \   \
        *    2  3      4   5
        *              |   /  | \
        *              6   7  8  9   */
       
        // Left child right sibling
        /*  10
        *    |
        *    2 -> 3 -> 4 -> 5
        *              |    |
        *              6    7 -> 8 -> 9  */
  
        let root = new NodeTemp(10);
        let n1 = addChild(root,2);
        let n2 = addChild(root,3);
        let n3 = addChild(root,4);
        let n4 = addChild(n3,6);
        let n5 = addChild(root,5);
        let n6 = addChild(n5,7);
        let n7 = addChild(n5,8);
        let n8 = addChild(n5,9);
          
        traverseTree(root);
 
 
 
// This code is contributed by patel2127
 
</script>


Output

 10 2 3 4 6 5 7 8 9

Level Order Traversal: The above code talks about depth-first traversal. We can also do level order traversal of such representation.

Implementation:

C++




// C++ program to create a tree with left child
// right sibling representation.
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    struct Node* next;
    struct Node* child;
};
 
// Creating new Node
Node* newNode(int data)
{
    Node* newNode = new Node;
    newNode->next = newNode->child = NULL;
    newNode->data = data;
    return newNode;
}
 
// Adds a sibling to a list with starting with n
Node* addSibling(Node* n, int data)
{
    if (n == NULL)
        return NULL;
 
    while (n->next)
        n = n->next;
 
    return (n->next = newNode(data));
}
 
// Add child Node to a Node
Node* addChild(Node* n, int data)
{
    if (n == NULL)
        return NULL;
 
    // Check if child list is not empty.
    if (n->child)
        return addSibling(n->child, data);
    else
        return (n->child = newNode(data));
}
 
// Traverses tree in level order
void traverseTree(Node* root)
{
    // Corner cases
    if (root == NULL)
        return;
 
    cout << root->data << " ";
 
    if (root->child == NULL)
        return;
 
    // Create a queue and enqueue root
    queue<Node*> q;
    Node* curr = root->child;
    q.push(curr);
 
    while (!q.empty()) {
 
        // Take out an item from the queue
        curr = q.front();
        q.pop();
 
        // Print next level of taken out item and enqueue
        // next level's children
        while (curr != NULL) {
            cout << curr->data << " ";
            if (curr->child != NULL) {
                q.push(curr->child);
            }
            curr = curr->next;
        }
    }
}
 
// Driver code
int main()
{
    Node* root = newNode(10);
    Node* n1 = addChild(root, 2);
    Node* n2 = addChild(root, 3);
    Node* n3 = addChild(root, 4);
    Node* n4 = addChild(n3, 6);
    Node* n5 = addChild(root, 5);
    Node* n6 = addChild(n5, 7);
    Node* n7 = addChild(n5, 8);
    Node* n8 = addChild(n5, 9);
    traverseTree(root);
    return 0;
}


Java




// Java program to create a tree with left child
// right sibling representation.
import java.util.*;
class GFG
{
  static class Node
  {
    int data;
    Node next;
    Node child;
  };
 
  // Creating new Node
  static Node newNode(int data)
  {
    Node newNode = new Node();
    newNode.next = newNode.child = null;
    newNode.data = data;
    return newNode;
  }
 
  // Adds a sibling to a list with starting with n
  static Node addSibling(Node n, int data)
  {
    if (n == null)
      return null;
    while (n.next != null)
      n = n.next;
    return (n.next = newNode(data));
  }
 
  // Add child Node to a Node
  static Node addChild(Node n, int data)
  {
    if (n == null)
      return null;
 
    // Check if child list is not empty.
    if (n.child != null)
      return addSibling(n.child, data);
    else
      return (n.child = newNode(data));
  }
 
  // Traverses tree in level order
  static void traverseTree(Node root)
  {
    // Corner cases
    if (root == null)
      return;
    System.out.print(root.data+ " ");
    if (root.child == null)
      return;
 
    // Create a queue and enqueue root
    Queue<Node> q = new LinkedList<>();
    Node curr = root.child;
    q.add(curr);
 
    while (!q.isEmpty())
    {
 
      // Take out an item from the queue
      curr = q.peek();
      q.remove();
 
      // Print next level of taken out item and enqueue
      // next level's children
      while (curr != null)
      {
        System.out.print(curr.data + " ");
        if (curr.child != null)
        {
          q.add(curr.child);
        }
        curr = curr.next;
      }
    }
  }
 
  // Driver code
  public static void main(String[] args)
  {
    Node root = newNode(10);
    Node n1 = addChild(root, 2);
    Node n2 = addChild(root, 3);
    Node n3 = addChild(root, 4);
    Node n4 = addChild(n3, 6);
    Node n5 = addChild(root, 5);
    Node n6 = addChild(n5, 7);
    Node n7 = addChild(n5, 8);
    Node n8 = addChild(n5, 9);
    traverseTree(root);
  }
}
 
// This code is contributed by aashish1995


Python3




# Python3 program to create a tree with
# left child right sibling representation
from collections import deque
 
class Node:
     
    def __init__(self, x):
         
        self.data = x
        self.next = None
        self.child = None
 
# Adds a sibling to a list with
# starting with n
def addSibling(n, data):
     
    if (n == None):
        return None
 
    while (n.next):
        n = n.next
 
    n.next = Node(data)
    return n
 
# Add child Node to a Node
def addChild(n, data):
     
    if (n == None):
        return None
         
    # Check if child list is not empty
    if (n.child):
        return addSibling(n.child, data)
    else:
        n.child = Node(data)
        return n
 
# Traverses tree in level order
def traverseTree(root):
     
    # Corner cases
    if (root == None):
        return
 
    print(root.data, end = " ")
 
    if (root.child == None):
        return
 
    # Create a queue and enqueue root
    q = deque()
    curr = root.child
    q.append(curr)
 
    while (len(q) > 0):
         
        # Take out an item from the queue
        curr = q.popleft()
        #q.pop()
 
        # Print next level of taken out
        # item and enqueue next level's children
        while (curr != None):
            print(curr.data, end = " ")
             
            if (curr.child != None):
                q.append(curr.child)
                 
            curr = curr.next
 
# Driver code
if __name__ == '__main__':
 
    root = Node(10)
    n1 = addChild(root, 2)
    n2 = addChild(root, 3)
    n3 = addChild(root, 4)
    n4 = addChild(n3, 6)
    n5 = addChild(root, 5)
    n6 = addChild(n5, 7)
    n7 = addChild(n5, 8)
    n8 = addChild(n5, 9)
     
    traverseTree(root)
 
# This code is contributed by mohit kumar 29


C#




// C# program to create a tree with left child
// right sibling representation.
using System;
using System.Collections.Generic;
class GFG
{
  public
    class Node
    {
      public
        int data;
      public
        Node next;
      public
        Node child;
    };
 
  // Creating new Node
  static Node newNode(int data)
  {
    Node newNode = new Node();
    newNode.next = newNode.child = null;
    newNode.data = data;
    return newNode;
  }
 
  // Adds a sibling to a list with starting with n
  static Node addSibling(Node n, int data)
  {
    if (n == null)
      return null;
    while (n.next != null)
      n = n.next;
    return (n.next = newNode(data));
  }
 
  // Add child Node to a Node
  static Node addChild(Node n, int data)
  {
    if (n == null)
      return null;
 
    // Check if child list is not empty.
    if (n.child != null)
      return addSibling(n.child, data);
    else
      return (n.child = newNode(data));
  }
 
  // Traverses tree in level order
  static void traverseTree(Node root)
  {
 
    // Corner cases
    if (root == null)
      return;
    Console.Write(root.data + " ");
    if (root.child == null)
      return;
 
    // Create a queue and enqueue root
    Queue<Node> q = new Queue<Node>();
    Node curr = root.child;
    q.Enqueue(curr);
    while (q.Count != 0)
    {
 
      // Take out an item from the queue
      curr = q.Peek();
      q.Dequeue();
 
      // Print next level of taken out item and enqueue
      // next level's children
      while (curr != null)
      {
        Console.Write(curr.data + " ");
        if (curr.child != null)
        {
          q.Enqueue(curr.child);
        }
        curr = curr.next;
      }
    }
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    Node root = newNode(10);
    Node n1 = addChild(root, 2);
    Node n2 = addChild(root, 3);
    Node n3 = addChild(root, 4);
    Node n4 = addChild(n3, 6);
    Node n5 = addChild(root, 5);
    Node n6 = addChild(n5, 7);
    Node n7 = addChild(n5, 8);
    Node n8 = addChild(n5, 9);
    traverseTree(root);
  }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// JavaScript program to create a
// tree with left child
// right sibling representation.
     
    class Node
    {
    // Creating new Node
        constructor(data)
        {
            this.data=data;
            this.next = this.child = null;
        }
    }
 
// Adds a sibling to a list with starting with n
function addSibling(n,data)
{
    if (n == null)
      return null;
    while (n.next != null)
      n = n.next;
    return (n.next = new Node(data));
}
 
// Add child Node to a Node
function addChild(n,data)
{
    if (n == null)
      return null;
  
    // Check if child list is not empty.
    if (n.child != null)
      return addSibling(n.child, data);
    else
      return (n.child = new Node(data));
}
 
// Traverses tree in level order
function traverseTree(root)
{
    // Corner cases
    if (root == null)
      return;
    document.write(root.data+ " ");
    if (root.child == null)
      return;
  
    // Create a queue and enqueue root
    let q = [];
    let curr = root.child;
    q.push(curr);
  
    while (q.length!=0)
    {
  
      // Take out an item from the queue
      curr = q[0];
      q.shift();
  
      // Print next level of taken out item and enqueue
      // next level's children
      while (curr != null)
      {
        document.write(curr.data + " ");
        if (curr.child != null)
        {
          q.push(curr.child);
        }
        curr = curr.next;
      }
    }
}
 
// Driver code
let root = new Node(10);
let n1 = addChild(root, 2);
let n2 = addChild(root, 3);
let n3 = addChild(root, 4);
let n4 = addChild(n3, 6);
let n5 = addChild(root, 5);
let n6 = addChild(n5, 7);
let n7 = addChild(n5, 8);
let n8 = addChild(n5, 9);
traverseTree(root);
 
 
// This code is contributed by unknown2108
 
</script>


Output

10 2 3 4 5 6 7 8 9 

Time Complexity: O(n), where n is the number of nodes in the tree.
Auxiliary Space: O(n)

This article is contributed by SAKSHI TIWARI. If you like GeeksforGeeks(We know you do!) 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. 


My Personal Notes arrow_drop_up

Next Article

Similar Reads

Left-Child Right-Sibling Representation of Tree
An n-ary tree in computer science is a collection of nodes normally represented hierarchically in the following fashion. The tree starts at the root node.Each node of the tree holds a list of references to its child nodes.The number of children a node has is less than or equal to n. A typical representation of n-ary tree uses an array of n referenc
15+ min read
Convert left-right representation of a binary tree to down-right
Left-Right representation of a binary tree is standard representation where every node has a pointer to left child and another pointer to right child.Down-Right representation is an alternate representation where every node has a pointer to left (or first) child and another pointer to next sibling. So siblings at every level are connected from left
10 min read
Find the sum of all left leaf nodes which also has its right sibling
Given a Binary Tree rooted at root, the task is to find the sum of all leaf nodes which are left child of their parents and which also have their right sibling i.e, it's a parent has also a right child. Examples: Input: 16 / \ 20 15 / / \ 100 21 25 / / \ / \27 14 9 7 6 / \ \ 17 12 2Output: 24.Explanation: The leaf nodes having values 7 and 17 only
8 min read
Right sibling of each node in a tree given as array of edges
Given a tree, with N nodes and E edges (every edge is denoted by two integers, X, Y stating that X is the parent of Y), the task is to print all the nodes with their right siblings in separate lines. If there is no right sibling for a particular node then print -1 instead. Examples: In the image shown above, nodes 3, 5, 6, 7 are the right siblings
7 min read
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? Examples: 1 / \ 2 3 / \ \ 4 6 5 / \ \ 7 9 8 / \ 10 12 Input : Given above tree with parent pointer and node 10 Output : 12 Recommended: Please solve it on PRACTICE f
10 min read
Print a matrix in alternate manner (left to right then right to left)
Given a 2D array, the task is to print the 2D in alternate manner (First row from left to right, then from right to left, and so on). Examples: Input : arr[][2] = {{1, 2} {2, 3}}; Output : 1 2 3 2 Input :arr[][3] = { { 7 , 2 , 3 }, { 2 , 3 , 4 }, { 5 , 6 , 1 }}; Output : 7 2 3 4 3 2 5 6 1 The solution of this problem is that run two loops and print
5 min read
Sum of nodes in a binary tree having only the left child nodes
Given a binary tree, the task is to find the sum of binary tree nodes having only the left child nodes. Example: Input: 8 / \ 3 7 / \ / 5 6 0 / / 1 2Output: 18 Explanation: Nodes with values 5, 6, and 7 are the ones that have only the left child nodes Input: 2 / \ 3 1 / / 5 6Output: 4 Approach: The given problem can be solved by traversing the bina
6 min read
Count of possible paths from top left to bottom right of a M x N matrix by moving right, down or diagonally
Given 2 integers M and N, the task is to find the count of all the possible paths from top left to the bottom right of an M x N matrix with the constraints that from each cell you can either move only to right or down or diagonally Examples: Input: M = 3, N = 3Output: 13Explanation: There are 13 paths as follows: VVHH, VHVH, HVVH, DVH, VDH, VHHV, H
14 min read
Maximum absolute difference between the sibling nodes of given BST
Given a BST (Binary Search Tree) with N Nodes, the task is to find the maximum absolute difference between the sibling nodes. Two nodes are said to be siblings if they are present at the same level, and their parents are the same.] Examples: Input: Output: 70Explanation:105 - 50 = 55 (As 105 and 50 nodes are siblings)75 - 5 = 70 (As 75 and 5 nodes
8 min read
Print all nodes that don't have sibling
Given a Binary Tree, print all nodes that don't have a sibling (a sibling is a node that has same parent. In a Binary Tree, there can be at most one sibling). Root should not be printed as root cannot have a sibling.For example, the output should be "4 5 6" for the following tree. Recommended PracticePrint all nodes that don't have siblingTry It! T
14 min read
Article Tags :
Practice Tags :