题目来源:
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
题意分析:
给出一颗二叉树的中序遍历和后续遍历,还原这个树。
题目思路:
这题和上一题类似,用递归的思想,先根据后序遍历的最后一个确定根节点,然后将中序遍历分成两部分,接着递归就可以了。
代码(python):
# 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
"""
def dfs(ibegin,iend,pbegin,pend):
if pbegin >= pend:
return None
if pbegin == pend - 1:
return TreeNode(postorder[pend - 1])
i = inorder.index(postorder[pend - 1]) - ibegin
ans = TreeNode(postorder[pend - 1])
ans.left = dfs(ibegin,ibegin+i,pbegin,pbegin + i)
ans.right = dfs(ibegin + 1 + i,iend,pbegin + i,pend - 1)
return ans
return dfs(0,len(inorder),0,len(postorder))