当前位置:首页python > 正文

二叉树(Binary Tree)基础知识

作者:野牛程序员:2025-12-22 11:34:40python阅读 2097
二叉树(Binary Tree)基础知识
# /*
# 二叉树(Binary Tree)基础知识
# --------------------------------------------------------
# 定义:
# 每个节点最多有两个子节点的树结构。
# - 左子节点(left)
# - 右子节点(right)
#
# 特点:
# - 根节点(root)唯一
# - 节点之间无环
# - 子树也是二叉树
#
# 常用操作:
# 1) 遍历:前序、中序、后序
# 2) 搜索:深度优先搜索(DFS)、广度优先搜索(BFS)
# 3) 插入 / 删除节点
# */

# 二叉树节点定义
class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

# --------------------------------------------------------
# 示例二叉树构建
#            A
#          /   \
#         B     C
#       /   \
#      D     E

root = TreeNode("A")
root.left = TreeNode("B")
root.right = TreeNode("C")
root.left.left = TreeNode("D")
root.left.right = TreeNode("E")

# --------------------------------------------------------
# 前序遍历(根 -> 左 -> 右)
def preorder(node):
    if node is None:
        return
    print(node.value, end=" ")
    preorder(node.left)
    preorder(node.right)

# 中序遍历(左 -> 根 -> 右)
def inorder(node):
    if node is None:
        return
    inorder(node.left)
    print(node.value, end=" ")
    inorder(node.right)

# 后序遍历(左 -> 右 -> 根)
def postorder(node):
    if node is None:
        return
    postorder(node.left)
    postorder(node.right)
    print(node.value, end=" ")

# --------------------------------------------------------
print("前序遍历结果:", end="")
preorder(root)
print()

print("中序遍历结果:", end="")
inorder(root)
print()

print("后序遍历结果:", end="")
postorder(root)
print()

# --------------------------------------------------------
# 要点总结:
# 1) 二叉树每个节点最多两个子节点;
# 2) 遍历方式有前序、中序、后序,访问顺序不同;
# 3) DFS、BFS 可用于二叉树搜索和层序遍历;
# 4) 可以用于实现二叉搜索树、堆、表达式树等数据结构。
# */


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
  • 二叉树(Binary Tree)基础知识
  • 相关推荐

    最新推荐

    热门点击