在 Python 中根据后序和中序构造二叉树
pythonserver side programmingprogramming更新于 2025/10/17 9:48:17
假设我们有一个二叉树的中序和后序遍历序列。我们必须根据这些序列生成树。因此,如果后序和中序序列为 [9,15,7,20,3] 和 [9,3,15,20,7],则树将为 −

让我们看看步骤 −
定义一个方法 build_tree(),它将采用 inorder、postorder −
如果 inorder 列表不为空 −
root := 使用 postorder 的最后一个值创建一个树节点,然后删除该元素
ind := inorder 列表中根数据的索引
root 的右侧 := build_tree(inorder 从索引 ind 到末尾,postorder)
root 的左侧 := build_tree(inorder 从 0 到索引 ind - 1,postorder)
返回
示例
让我们看看下面的实现以便更好地理解 −
class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def print_tree(root): if root is not None: print_tree(root.left) print(root.data, end = ', ') print_tree(root.right) class Solution(object): def buildTree(self, inorder, postorder): if inorder: root = TreeNode(postorder.pop()) ind = inorder.index(root.data) root.right = self.buildTree(inorder[ind+1:],postorder) root.left = self.buildTree(inorder[:ind],postorder) return root ob1 = Solution() print_tree(ob1.buildTree([9,3,15,20,7], [9,15,7,20,3]))
输入
[9,3,15,20,7] [9,15,7,20,3]
输出
[9,3,15,20,7]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

