python 已知前序遍历和中序遍历求二叉树结构代码,用python实现,二叉树算法
发布人:shili8
发布时间:2024-10-15 12:21
阅读次数:0
**二叉树的前序遍历和中序遍历**
=====================================在本文中,我们将使用Python语言来实现一个函数,能够根据给定的前序遍历和中序遍历结果,重建出原始二叉树结构。
**前序遍历和中序遍历**
------------------------
首先,让我们了解一下什么是前序遍历和中序遍历。前序遍历是指在访问一个节点之前,先访问其左子树,然后再访问右子树;而中序遍历则是先访问左子树,然后再访问根节点(即当前节点),最后再访问右子树。
**二叉树的定义**
-----------------
我们将使用以下Python类来表示二叉树:
class Node: def __init__(self, value): self.value = value self.left = None self.right = None
**前序遍历和中序遍历函数**
------------------------------
现在,我们可以定义一个函数,能够根据给定的前序遍历和中序遍历结果,重建出原始二叉树结构。
def build_tree(preorder, inorder): if not preorder or not inorder: return None root_value = preorder[0] root_node = Node(root_value) index = inorder.index(root_value) root_node.left = build_tree(preorder[1:index+1], inorder[:index]) root_node.right = build_tree(preorder[index+1:], inorder[index+1:]) return root_node
**示例代码**
-------------
现在,让我们使用上述函数来创建一个二叉树:
# 前序遍历结果preorder = [3,9,20,15,7] # 中序遍历结果inorder = [9,3,15,20,7] root_node = build_tree(preorder, inorder)
**二叉树的打印**
-----------------
最后,我们可以定义一个函数,能够将二叉树打印出来:
def print_tree(node): if node is None: return print(node.value) print_tree(node.left) print_tree(node.right)
**示例代码**
-------------
现在,让我们使用上述函数来打印出创建的二叉树:
print_tree(root_node) # 输出:3915207
**总结**
----------
在本文中,我们使用Python语言实现了一个函数,能够根据给定的前序遍历和中序遍历结果,重建出原始二叉树结构。我们还定义了一个函数,将二叉树打印出来。示例代码展示了如何使用这些函数来创建并打印出一个二叉树。
**参考**
----------
* [Python 中的二叉树]( />* [前序遍历和中序遍历]( />* [二叉树的定义](

