题目
思路
思路同 从前序与中序遍历序列构造二叉树,区别是root需要从postorder列表的尾部取。
# 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]:
# 如果所有节点都已经扫过,说明新的树已经建成了,应返回空节点
if not inorder:
return None
# 1.取出后序节点创建新树的节点
root = TreeNode(postorder[-1])
# 2.找到新树的节点在中序中的索引
in_index = inorder.index(root.val)
# 3.分割中序序列
in_left = inorder[:in_index]
in_right = inorder[in_index+1:]
# 4.分割后序序列
pre_left = postorder[:len(in_left)]
pre_right = postorder[len(in_left):-1]
# 5.继续递归建立整颗新树
root.left = self.buildTree(in_left, pre_left)
root.right = self.buildTree(in_right, pre_right)
return root

该文章介绍了一种方法,通过给定的后序遍历和中序遍历序列来构建二叉树。首先,从后序遍历序列的末尾获取根节点,然后在中序遍历序列中找到根节点的索引,以此将中序序列分为左右两部分。接着,分别对这两部分进行递归,构建左子树和右子树,最终完成整个二叉树的构建。
946

被折叠的 条评论
为什么被折叠?



