-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlevel_order.py
More file actions
executable file
·56 lines (44 loc) · 1.09 KB
/
level_order.py
File metadata and controls
executable file
·56 lines (44 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/python
# vim: foldlevel=0
"""
Level ordering of binary search tree.
"""
from collections import deque
from bintree import randbintree
def level_order_iterative(root):
queue = deque()
queue.appendleft(root)
while queue:
node = queue.pop()
print node.key
if node.left:
queue.appendleft(node.left)
if node.right:
queue.appendleft(node.right)
def height(node):
if not node:
return 0
lheight = height(node.left)
rheight = height(node.right)
if lheight > rheight:
return lheight + 1
else:
return rheight + 1
def print_level(root, level):
if not root:
return
if level == 1:
print root.key
else:
print_level(root.left, level-1)
print_level(root.right, level-1)
def level_order_recursive(root):
h = height(root)
for level in range(1, h+1):
print_level(root, level)
if __name__ == "__main__":
t = randbintree()
print "The binary tree"
t.print_tree()
print "Level order traversal"
level_order_iterative(t.root)