Unit III - Topic 2 - Left-Child Right-Sibling Data Structures For General Trees
Unit III - Topic 2 - Left-Child Right-Sibling Data Structures For General Trees
An n-ary tree in computer science is a collection of nodes normally represented hierarchically in the following
fashion.
1. The tree starts at the root node.
2. Each node of the tree holds a list of references to its child nodes.
3. 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 references (or pointers) to store children (Note that n is an
upper bound on number of children). The idea of Left-Child Right- Sibling representation is to store only two
pointers in every node.
It 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. One thing to
note is that in the previous representation a link between two nodes denoted a parent-child relationship whereas in
this representation a link between two nodes may denote a parent-child relationship or a sibling-sibling
relationship.
Advantages :
1. This representation saves up memory by limiting the maximum number of references required per node to two.
2. It is easier to code.
1
UNIT III – Topic 2 - LEFT-CHILD RIGHT-SIBLING DATA STRUCTURES FOR GENERAL TREES
Disadvantages :
1. Basic operations like searching/insertion/deletion tend to take a longer time because in order to find the
appropriate position we would have to traverse through all the siblings of the node to be searched/inserted/deleted
(in the worst case).
The image on the left is the normal representation of a 6-ary tree and the one on the right is it’s corresponding
Left-Child Right-Sibling representation.
2
UNIT III – Topic 2 - LEFT-CHILD RIGHT-SIBLING DATA STRUCTURES FOR GENERAL TREES
#include<stdio.h>
#include<stdlib.h>
struct Node
int data;
};
3
UNIT III – Topic 2 - LEFT-CHILD RIGHT-SIBLING DATA STRUCTURES FOR GENERAL TREES
newNode->data = data;
return newNode;
if (n == NULL)
return NULL;
while (n->next)
n = n->next;
if (n == NULL)
4
UNIT III – Topic 2 - LEFT-CHILD RIGHT-SIBLING DATA STRUCTURES FOR GENERAL TREES
return NULL;
if (n->child)
else
if (root == NULL)
return;
while (root)
if (root->child)
5
UNIT III – Topic 2 - LEFT-CHILD RIGHT-SIBLING DATA STRUCTURES FOR GENERAL TREES
traverseTree(root->child);
root = root->next;
//Driver code
int main()
* 10
* //\\
*23 45
* |/|\
* 6 7 8 9 */
/* 10
6
UNIT III – Topic 2 - LEFT-CHILD RIGHT-SIBLING DATA STRUCTURES FOR GENERAL TREES
*|
* ||
* 6 7 -> 8 -> 9 */
traverseTree(root);
return 0;