# Creating a tree with Left-Child Right-Sibling Representation

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 it’s first child, and the other to it’s immediate next sibling. This new transformation not only removes the need of advance 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
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Prerequisite : Left-Child Right-Sibling Representation of Tree

```// CPP 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
{
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)
else
return (n->child = newNode(data));
}

// Traverses tree in level 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);
traverseTree(root);
return 0;
}
```

Output:

```10 2 3 4 6 5 7 8 9
```

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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
3.2 Average Difficulty : 3.2/5.0
Based on 4 vote(s)