-3

I need help with this problem. Example tree:

                         A
                        /
                       B-C-D
                           /
                           E-F-G

I have a binary tree that represents ordered tree and I have to count the number of children for each node and place that number in corresponding node.

There are three children(B,C,D) for A and three(E,F,G) for D. Zero children for B,C,E,F,G.

Every node only can have two children in physical (binary) representation. If a node has a left child then every right child from this node on is considered a child too. In my example A left child is B. B has one right child C. C has one right child D. So B, C and D are children for A in this task..

At the end of the program the data in nodes should be A(3),B(0),C(0),D(3),E(0),F(0),G(0).

madth3
  • 7,275
  • 12
  • 50
  • 74
VOid
  • 85
  • 2
  • 13
  • 1
    A binary tree by definition cannot have more than 2 children per node. What are you asking? We know nothing about what the format of the input is. – Rob Volgman Jun 11 '13 at 19:05
  • If a node has a left child then its children are this left child and all the nodes going right from this left child. – VOid Jun 11 '13 at 19:11
  • ...that's still not a binary tree – Joe Runde Jun 11 '13 at 19:13
  • Every node only can have two children in physical representation. If a node has a left child then every right child from this node on is considered a child too. In my example A left child is B. B has one right child C. C has one right child D. So B, C and D are children for A in this task... – VOid Jun 11 '13 at 19:16

1 Answers1

0

What you are describing seems like an arbitrary-arity tree represented in a left-child right-sibling pattern. Each node holds a pointer to its left-most child as well as its right sibling.

Finding how many children a given node has shouldn't be too difficult. Just take the left-most child and then count how many times you can iterate to its right sibling. In pseudocode it would look something like this:

def Node {
    Node* left_child
    Node* right_sibling
}

numChildren(Node n) {
    num = 0
    next = n.left_child
    while (next exists)
        num = num + 1
        next = next.right_sibling
    return num
}
CygnusX1
  • 20,968
  • 5
  • 65
  • 109