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?
The main problem here is that you are using deepcopy on the temporary list. Consider what happens each 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
Nonefor.leftand.right)