Search code examples
c++data-structurestreestructurechild-nodes

How to create a tree with the number of child nodes being decided at run time?


As far as i know trees are created using structures and the trees i have created have always had nodes with the same no. of child nodes which is decided at compile time, like

struct node
{
int data;
struct node *left,*right;
};

which has 2 child nodes decided during compile time.How do i decide the no. of child nodes(which is constant for all nodes) during run time? Also is it possible to create a tree in which the child nodes for every node are decided during run time?


Solution

  • Here's a simple way to do it in Python (2.7) : you pass a list of children to the constructor, so you can decide on how many children you need at when you run the code:

    class TreeNode:
        def __init__(self, data):
            self.data = data
            self.children = []
    
        def add_children(self, child):
            self.children.append(child)
    
        def __str__(self):
            return str(self.data)
    
        def print_tree(self, root):
            if root is None:
                return
            print root.data
            for child in root.children:
                self.print_tree(child)
    
    r = TreeNode(0)
    ch1 = TreeNode(1)
    ch2 = TreeNode(2)
    ch3 = TreeNode(3)
    r.add_children(ch1)
    r.add_children(ch2)
    r.add_children(ch3)
    ch4 = TreeNode(4)
    ch1.add_achildren(ch4)
    
    >>> r.print_tree(r)
    0
    1
    4
    2
    3
    

    '>>>' is run from the interpreter.