Problem building a complete binary tree of height 'h' in Python

Posted by Jack on Stack Overflow See other posts from Stack Overflow or by Jack
Published on 2010-04-08T13:56:10Z Indexed on 2010/04/08 14:33 UTC
Read the original article Hit count: 359

Filed under:
|
|

Here is my code. The complete binary tree has 2^k nodes at depth k.

class Node:

    def __init__(self, data):
        # initializes the data members
        self.left = None
        self.right = None
        self.data = data


root = Node(data_root)

def create_complete_tree():
        row = [root]

        for i in range(h):

            newrow = []
            for node in row:
                left = Node(data1)  
                right = Node(data2)  

                node.left = left
                node.right = right

                newrow.append(left)
                newrow.append(right)


            row = copy.deepcopy(newrow)



def traverse_tree(node):
        if node == None:
            return
        else:
            traverse_tree(node.left)
            print node.data
            traverse_tree(node.right)

create_complete_tree()

print 'Node traversal'

traverse_tree(root)

The tree traversal only gives the data of root and its children. What am I doing wrong?

© Stack Overflow or respective owner

Related posts about python

Related posts about beginner