- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBinaryLevelPrint.py
More file actions
Latest commit
59 lines (55 loc) · 1.28 KB
/
Copy pathBinaryLevelPrint.py
File metadata and controls
59 lines (55 loc) · 1.28 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
57
58
59
classTreeNode(object):
'''
tree node for binary tree
'''
def__init__(self,data=None,left=None, right=None):
self.data=data
self.left=left
self.right=right
classBinaryTree(object):
'''
Binary Tree
'''
def__init__(self,root):
self.root=root
deflevel_print(self):
'''
print binary tree by level
'''
thisLevel= [self.root]
whilethisLevel:
nextLevel= []
print [i.dataforiinthisLevel]
fornodeinthisLevel:
ifnode.leftisnotNone:
nextLevel.append(node.left)
ifnode.rightisnotNone:
nextLevel.append(node.right)
thisLevel=nextLevel
defbfs(self):
'''
breath first search to print the tree
'''
queue= [self.root]
whilequeue:
# print [i.data for i in queue]
node=pop(0)
printnode.data
ifnode.left:
queue.append(node.left)
ifnode.right:
queue.append(node.right)
defdfs(self):
'''
depth first search to print the tree
'''
# stack last in first out
stack= [self.root]
whilestack:
node=stack.pop()
printnode.data
ifnode.right:
stack.append(node.right)
ifnode.left:
# pop left first
stack.append(node.left)