题目描述
根据一棵树的中序遍历与后序遍历构造二叉树。
注意: 你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
我的解法——递归(AC)
# 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 mybuildTree(self, inorder, postorder, l1, r1, l2, r2, dic):
now = TreeNode(postorder[r2])
index = dic[postorder[r2]]
left_count = index - l1
right_count = r1 - index
if(left_count > 0):
now.left = self.mybuildTree(inorder, postorder, l1, index - 1, l2, l2 + left_count - 1, dic)
if(right_count > 0):
now.right = self.mybuildTree(inorder, postorder, index + 1, r1, l2 + left_count, r2 - 1, dic)
return now
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
if(not len(inorder) or not len(postorder)):
return None
dic = {}
for i in range(len(inorder)):
dic[inorder[i]] = i
return self.mybuildTree(inorder, postorder, 0, len(inorder) - 1, 0, len(postorder) - 1, dic)