-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlevelorder.py
More file actions
54 lines (43 loc) · 1.13 KB
/
levelorder.py
File metadata and controls
54 lines (43 loc) · 1.13 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
__author__ = 'cue'
from collections import deque
class node (object):
level = 0
data = ''
child = []
def __init__(self,data):
self.data = data
self.child = []
def add_child(self,ch):
ch.level = self.level + 1
self.child.append(ch)
def levelorder(root):
temproot =root
que = deque()
currentlevel = 0
while temproot is not None:
if currentlevel != temproot.level:
currentlevel = temproot.level
print ("")
print (temproot.data, end='')
countchild = len(temproot.child)
if countchild != 0:
que.extend(temproot.child)
if len(que) == 0:
break
temproot = que.popleft()
def print_tree (root):
print (root.data, "level",root.level)
for chil in root.child:
print_tree(chil)
if __name__ == '__main__':
root = node('A')
child1 = node('B')
child2 = node('C')
child3 = node('D')
child3_1 = node('E')
root.add_child(child1)
root.add_child(child2)
root.add_child(child3)
child3.add_child(child3_1)
levelorder(root)
#print_tree(root)