用 Python 从中序和后序遍历构造二叉树
假设我们具有二叉树的中序和后序遍历序列。我们必须根据这些序列生成树。所以如果后序和中序序列分别为:[9,15,7,20,3] 和 [9,3,15,20,7],那么树将为 −

让我们了解各步骤 −
- 假定该方法以先序和中序列表作为 buildTree 参数
- 根 := 后序列表中的最后一个结点,并从后序列表中删除第一个结点
- 根_索引 := 根值在中序列表中的索引
- 左子树或根 := buildTree(中序列表中索引从根索引 + 1 到尾部的子集,后序列表)
- 右子树或根 := buildTree(中序列表中索引从 0 到根索引的子集,后序列表)
让我们了解以下实现,以便更好地理解 −
示例
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([9,3,15,20,7], [9,15,7,20,3]))
输入
[9,3,15,20,7] [9,15,7,20,3]
输出
9, 15, 7, 20, 3,
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP