今天我们将介绍二叉树的理论和实践基础以及遍历它的方法。
树通常是图族的子集,其构建和管理遵循一定的规则。
二叉树是一种具体的数据结构,其中每个节点最多有两个子节点。通常每个节点都有 3 个属性:data、leftchild 和 rightchild。
它用于按“标准”对不同类型的二叉树进行分类。
让我们看看那里存在哪些类型(类):
让我们分别看看每种类型。
如果您想更深入地了解其中每一个,这里有完整的概述。
很好,现在我们从概念上了解什么是二叉树以及可能的类型。

现在,让我们编写代码。回想一下,二叉树由节点组成,每个节点都有数据、leftchild 和 rightchild 属性。
from typing import any
class treenode:
def __init__(self, data: any):
self.data = data
self.left = none
self.right = none
# define all the nodes we need
root = treenode('r')
nodea = treenode('a')
nodeb = treenode('b')
nodec = treenode('c')
noded = treenode('d')
# connect all the nodes between each other
root.left = nodea
root.right = nodeb
nodea.left = nodec
nodea.right = noded
# what we've got
r
/ \
a b
/ \
c d
接下来至关重要的就是如何遍历二叉树。
1 先进的多级用户及代理商管理功能 2 透明的会员资金管理,系统自动完成会员资金的管理业务。 3 规范的业务流程,客户提交订单--业务人员受理订单--技术人员开通业务,简单,规范,使用的企业管理更加规范化。 4 便捷安装接入,只要把你的前台链接到我们指定的入口,其它的业务管理全部由系统自动完成。 5 领先的产品及菜单管理功能。可对产品和会员的菜单进行动态的增加、修改、删除,从而使用轻松方便的增加新
0
通常来说,遍历二叉树主要有2种方式(类型),广度优先搜索(bfs)和深度优先搜索(dfs)。
bfs 表示在进入树中的下一层之前访问同一级别的节点。这意味着树是在更侧面的方向上探索的。
dfs 代表当遍历树一直向下移动到叶节点时,向下逐枝探索树。
此外,dfs 遍历还有三种类型:
"""
preorder - is done by visiting the root node first, then recursively do a pre-order traversal of the left subtree, followed by a recursive pre-order traversal of the right subtree.
this traversal is "pre" order because the node is visited "before" the recursive pre-order traversal of the left and right subtrees.
"""
def pre_order(node):
if node:
print(node.value)
pre_order(node.left)
pre_order(node.right)

"""
postorder - works by recursively doing a post-order traversal of the left subtree and the right subtree, followed by a visit to the root node.
what makes this traversal "post" is that visiting a node is done "after" the left and right child nodes are called recursively.
"""
def post_order(node):
if node:
post_order(node.left)
post_order(node.right)
print(node.value)

"""
inOrder - does a recursive In-order Traversal of the left subtree, visits the root node, and finally, does a recursive In-order Traversal of the right subtree.
What makes this traversal "in" order, is that the node is visited in between the recursive function calls. The node is visited after the In-order Traversal of the left subtree, and before the In-order Traversal of the right subtree.
"""
def in_order(node):
if node:
in_order(node.left)
print(node.value)
in_order(node.right)

今天就这样。总结一下,我们修改了什么是二叉树,它的类型按标准划分,以及遍历它的方法是什么。
以上就是与你交谈系列#3的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号