面试150 从中序与后序遍历构造二叉树
思路
本题的突破口在于后序遍历。由于后序遍历的最后一个元素对应的是整棵树的根节点,因此我们可以首先根据该值创建根节点。接着,在中序遍历中定位该根节点的下标,并以此将中序遍历划分为左子树和右子树的部分。根据中序遍历中左右子树的长度,我们进一步划分后序遍历中对应的左右子树部分。最后,递归构建左右子树,并返回根节点即可完成整棵二叉树的构建。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:def construct(inorder,postorder):if not postorder:return Nonevalue=postorder[-1] #根节点root=TreeNode(value)Index=inorder.index(value)inorder_left=inorder[:Index]inorder_right=inorder[Index+1:]postorder_left=postorder[:len(inorder_left)]postorder_right=postorder[len(inorder_left):len(postorder)-1]root.left=construct(inorder_left,postorder_left)root.right=construct(inorder_right,postorder_right)return rootreturn construct(inorder,postorder)