开发者

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

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 = c开发者_开发技巧opy.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?


The main problem here is that you are using deepcopy on the temporary list. Consider what happens each iteration:

  1. Your initial root gets inspected, and child nodes get created
  2. These child nodes are placed in newrow
  3. Copies of these child nodes are copied into row for the next iteration.

This means the subsequent iteration will not be mutating the nodes you created (and which root.left and root.right points to), but copies of them, leaving the originals in their current state (with None for .left and .right)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜