-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathConstructBinaryTreeFromInorderAndPostorderTraversal_v0.py
More file actions
60 lines (47 loc) · 1.26 KB
/
ConstructBinaryTreeFromInorderAndPostorderTraversal_v0.py
File metadata and controls
60 lines (47 loc) · 1.26 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
60
#!/usr/bin/env python
# encoding: utf-8
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {integer[]} inorder
# @param {integer[]} postorder
# @return {TreeNode}
def buildTree(self, inorder, postorder):
if not inorder or not postorder:
return
n = postorder.pop()
t = TreeNode(n)
k = inorder.index(n)
t.right = self.buildTree(inorder[k+1:], postorder)
t.left = self.buildTree(inorder[:k], postorder)
return t
def inorder(self, root):
if not root:
return
self.inorder(root.left)
print root.val
self.inorder(root.right)
def postorder(self, root):
if not root:
return
self.postorder(root.left)
self.postorder(root.right)
print root.val
def preorder(self, root):
if not root:
return
print root.val
self.preorder(root.left)
self.preorder(root.right)
if __name__ == '__main__':
s = Solution()
h = s.buildTree([2,1,4,3,5], [2,4,5,3,1])
s.preorder(h)
print '-' * 6
s.inorder(h)
print '-' * 6
s.postorder(h)