algoritmauzmanı
Sign in
TREN
6.6Tree Applications
Lesson 6.6.3

General trees: first child, next sibling

In the tree from What is a tree? one node had three children. A folder in a file system can have hundreds of subfolders. In such general trees you cannot know how many pointers to set aside for each node. The fix is surprisingly simple: each node keeps only two pointers, to its first child and to its next sibling. In this lesson you see this form and the preorder traversal of a general tree.

What you will learn
  • How to keep nodes with many children using two pointers
  • How to add a child to a node
  • Preorder on a general tree, and why this form is really a binary tree
6 minTime O(n)Memory O(h)C · Java · Python

1Idea

The first idea is to give each node as many pointers as it has children, as in struct GNode* children[10]. But you must know the largest number of children in advance, and since most nodes are leaves, most of those pointers stay empty.

In the first child, next sibling form (also called left-child right-sibling) every node has two pointers:

  • child: the node's first (leftmost) child. NULL for a leaf.
  • sibling: the next child of the same parent, the sibling to the right. NULL for the last sibling.

All children of a node form a linked list that starts at the first child. The parent only keeps the head of that list. Adding a child means adding a node at the end of the list; the addChild function does that.

In the drawing, the arrows going down are child pointers and the arrows going right are sibling pointers. 1 has the children 2, 3 and 4; but 1 only points to 2, and 3 and 4 are reached through 2's sibling chain.

This is really a binary tree

Each node has two pointers: treat child as the left child and sibling as the right child. Then every general tree becomes a and code written for binary trees can be used. The preorder of this binary tree is the same as the preorder of the general tree. Since the root's sibling is always NULL, the root of the converted tree has no right child.

On a general tree, preorder is defined like this: visit the node first, then traverse its children in preorder from left to right. Postorder visits all the children first and the node last. Inorder is not defined for general trees, because there is no single "middle" place to write the root.

With the same idea you can keep a forest as one binary tree: make the root of the second tree the sibling of the root of the first.

2Step by step

In the tree, 1 has the children 2, 3 and 4; 2 has 5 and 6; 4 has 7. preorder(1) is called. The orange node is the one being printed and the orange arrow is the pointer followed to get there. The box on the right is the output.

1234567
Output
  1. preorder(1). The node is not NULL; it is printed first: 1.
  2. 1's first child is found through child: 2. preorder(2) is called and 2 is printed.
  3. 2's first child is 5. preorder(5) prints 5. 5's child is NULL, so its loop never runs.
  4. The loop in preorder(2) moves to the next sibling: 5's sibling is 6. 6 is printed; it has no children either.
  5. 6's sibling is NULL: 2's children are done and preorder(2) returns. The loop in preorder(1) moves on to 2's sibling: 3 is printed.
  6. 3 has no children. The loop moves to 3's sibling, 4: 4 is printed.
  7. 4's first child is 7: 7 is printed. 7 has no sibling, 4 has no sibling; all calls return.
  8. The traversal is done. Output: 1 2 5 6 3 4 7. Each node was printed once, after its parent and before its children.

struct GNode {    int data;    struct GNode* child;     // first child    struct GNode* sibling;   // next sibling}; struct GNode* newNode(int value) {    struct GNode* n = malloc(sizeof(struct GNode));    n->data = value;    n->child = NULL;    n->sibling = NULL;    return n;} void addChild(struct GNode* parent, struct GNode* child) {    if (parent->child == NULL) {            // the first child        parent->child = child;        return;    }    struct GNode* last = parent->child;    while (last->sibling != NULL)           // walk to the last sibling        last = last->sibling;    last->sibling = child;} void preorder(struct GNode* n) {    if (n == NULL) return;    printf("%d ", n->data);                 // the node itself first    for (struct GNode* c = n->child; c != NULL; c = c->sibling)        preorder(c);                        // then each child, left to right}
class GNode {    int data;    GNode child;     // first child    GNode sibling;   // next sibling    GNode(int data) { this.data = data; }} void addChild(GNode parent, GNode child) {    if (parent.child == null) {             // the first child        parent.child = child;        return;    }    GNode last = parent.child;    while (last.sibling != null)            // walk to the last sibling        last = last.sibling;    last.sibling = child;} void preorder(GNode n) {    if (n == null) return;    System.out.print(n.data + " ");         // the node itself first    for (GNode c = n.child; c != null; c = c.sibling)        preorder(c);                        // then each child, left to right}
class GNode:    def __init__(self, data):        self.data = data        self.child = None     # first child        self.sibling = None   # next sibling  def add_child(parent, child):    if parent.child is None:             # the first child        parent.child = child        return    last = parent.child    while last.sibling is not None:      # walk to the last sibling        last = last.sibling    last.sibling = child  def preorder(n):    if n is None:        return    print(n.data, end=" ")               # the node itself first    c = n.child    while c is not None:        preorder(c)                      # then each child, left to right        c = c.sibling

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

Each node is printed once and each pointer is followed once. O(n) for a tree with n nodes.

Memory
O(h)

The recursion goes as deep as the height h of the tree: O(h). Siblings are walked with a loop, so the number of siblings does not add depth.

addChild walks to the last sibling, so it takes as long as the number of children. If the order of the children does not matter, you can add the new child at the head of the list and make it O(1).

4Common mistake

The most common mistake is to visit siblings by recursion while also keeping the loop:

printf("%d ", n->data);for (struct GNode* c = n->child; c != NULL; c = c->sibling)    preorder(c);preorder(n->sibling);   // wrong: the loop already visits the siblings

Then each sibling is called both from its parent's loop and from the sibling on its left, and gets printed more than once. Use either the loop or recursion through sibling, not both.

5Try it

In the first child, next sibling form a node has 4 children. To how many of them does the parent keep a direct pointer?

Show the answer

The answer is B. The parent's child pointer points to the first child. The other children are reached through the sibling chain, by following sibling pointers.

If child is treated as the left child and sibling as the right child, what can you say about the root's right child?

Show the answer

The answer is A. The root has no siblings, so its sibling is NULL. That is why the root of the converted binary tree never has a right child.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.