题目:
题目链接: https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
解题思路:
类似从前序与中序遍历序列构造二叉树,需要注意的有几点:
- 根据后序遍历,当前最后一个元素为根节点
- 因为后续遍历是左子树 -> 右子树 -> 根节点的顺序,所以在递归调用的时候,应该先给右子树赋值,再给左子树赋值,顺序相反
代码实现:
# 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:
def build_help(inorder, postorder):
if 0 == len(inorder) or 0 == len(postorder):
return None
val = postorder[-1]
if val not in inorder:
return None
idx = inorder.index(val)
postorder.pop()
curr_root = TreeNode(val)
curr_root.right = build_help(inorder[idx + 1:], postorder)
curr_root.left = build_help(inorder[:idx], postorder)
return curr_root
if 0 == len(inorder) or 0 == len(postorder) or len(inorder) != len(postorder):
return None
return build_help(inorder, postorder)