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

让我们看看 − 的步骤
- 假设该方法使用前序和中序列表调用 buildTree
- root := 来自前序的第一个节点,并从前序中删除第一个节点
- root_index := 来自中序列表的 root.val 的索引
- left or root := buildTree(preorder, 从 0 到root_index)
- right or root := buildTree(preorder, 从 root_index + 1 到 end 的 inorder 子集)
让我们看看下面的实现以便更好地理解 −
示例
class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def print_tree(root): #print using inorder traversal if root is not None: print_tree(root.left) print(root.data, end = ',') print_tree(root.right) class Solution(object): def buildTree(self, preorder, inorder): if inorder: root = TreeNode(preorder.pop(0)) root_index = inorder.index(root.data) root.left = self.buildTree(preorder,inorder[:root_index]) root.right = self.buildTree(preorder,inorder[root_index+1:]) return root ob1 = Solution() print_tree(ob1.buildTree([3,9,20,15,7], [9,3,15,20,7]))
输入
[3,9,20,15,7] [9,3,15,20,7]
输出
9, 3, 15, 20, 7,
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

