Leetcode 106.根据中序和后序遍历构造二叉树

106.根据中序和后序遍历构造二叉树

题目

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

1
2
3
4
5
6
7
8
9
10
11
例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:

3
/ \
9 20
/ \
15 7

方法

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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
inorder: (inorder of left branch) root (inorder of right branch)
postorder: (postorder of left branch) (postorder of right branch) root
"""
length=len(inorder)
if length==0:
return
root=TreeNode(postorder[-1])
if length==1:
return root

i=inorder.index(postorder[-1])
root.left=self.buildTree(inorder[:i],postorder[:i])
root.right=self.buildTree(inorder[i+1:],postorder[i:-1])
return root
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
前序遍历是中左右,中序为左中右,后序为左右中,因此在中序中定位了根的位置就可以知道在前序和后续左右子树的划分
"""
if not postorder:
return None
root = TreeNode(postorder[-1])
n = inorder.index(postorder[-1])
root.left = self.buildTree(inorder[:n],postorder[:n])
root.right = self.buildTree(inorder[n+1:],postorder[n:-1])
return root