Python-二叉树

from collections import deque


class BiTreeNode:
    def __init__(self, data):
        self.data = data
        self.lchild = None  # 左孩子
        self.rchild = None  # 右孩子


a = BiTreeNode("A")
b = BiTreeNode("B")
c = BiTreeNode("C")
d = BiTreeNode("D")
e = BiTreeNode("E")
f = BiTreeNode("F")
g = BiTreeNode("G")
e.lchild = a
e.rchild = g
a.rchild = c
c.lchild = b
c.rchild = d
g.rchild = f

root = e


def pre_order(root):  # 前序遍历
    if root:
        print(root.data, end=',')
        pre_order(root.lchild)
        pre_order(root.rchild)


def in_order(root):  # 中序遍历
    if root:
        in_order(root.lchild)
        print(root.data, end=',')
        in_order(root.rchild)


def post_order(root):  # 后序遍历
    if root:
        post_order(root.lchild)
        post_order(root.rchild)
        print(root.data, end=',')


def level_order(root):  # 层次遍历
    queue = deque()
    queue.append(root)
    while len(queue) > 0:  # 队不空
        node = queue.popleft()  # 队首出队
        print(node.data, end=',')
        if node.lchild:
            queue.append(node.lchild)
        if node.rchild:
            queue.append(node.rchild)

print("前序遍历:")
pre_order(root)

print()
print("中序遍历:")
in_order(root)

print()
print("后序遍历:")
post_order(root)

print()
print("层次遍历:")
level_order(root)

 

 

posted on 2023-02-01 15:17  夜黎i  阅读(25)  评论(0)    收藏  举报

导航