题目
思路
- 后序遍历的分布为 [左子树结点,右子树结点,根结点]
- 后序遍历的最后一个元素为根节点
- 获取根节点在中序遍历中的索引
- 索引值变向的告诉了我们左右子树节点数
- 根据节点数可将后续遍历中的左右子树区分开
- 分别对左右子树递归获取根节点
python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not postorder:
return None
root = TreeNode(postorder[-1])
index = inorder.index(root.val)
root.left = self.buildTree(inorder[:index], postorder[:index])
root.right = self.buildTree(inorder[index+1:], postorder[index:-1])
return root