-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTree.py
More file actions
59 lines (47 loc) · 1009 Bytes
/
Copy pathbinaryTree.py
File metadata and controls
59 lines (47 loc) · 1009 Bytes
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
#Binary tree
#...............................
class Node(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def preorderTraversal(self, root):
if root is None:
return []
l=[root.val,]
l+=self.preorderTraversal(root.left)
l+=self.preorderTraversal(root.right)
return l
def inorderTraversal(self, root):
if root is None:
return []
output=[]
output+=self.inorderTraversal(root.left)
output.append(root.val)
output+=self.inorderTraversal(root.right)
return output
def postorderTraversal(self, root):
if root is None:
return []
l=[]
l+=self.postorderTraversal(root.left)
l+=self.postorderTraversal(root.right)
l.append(root.val)
return l
def levelOrder(self, root):
if root is None:
return []
output=[]
queue=[root,]
while queue:
l=[]
Q2=[]
for n in queue:
l.append(n.val)
if n.left is not None:
Q2.append(n.left)
if n.right is not None:
Q2.append(n.right)
queue=Q2
output.append(l)
return output