Python 二叉树遍历

48 阅读1分钟

以下图为例构建二叉树

未标题-1.jpg

代码实现

class TreeNode:
    def __init__(self) -> None:
        self.left:TreeNode = None
        self.right:TreeNode = None
        self.value = ""
        pass

A = TreeNode()
A.value = "A"

B = TreeNode()
B.value = "B"

C = TreeNode()
C.value = "C"

D = TreeNode()
D.value = "D"

E = TreeNode()
E.value = "E"

F = TreeNode()
F.value = "F"

G = TreeNode()
G.value = "G"

A.left = C
A.right = F

C.left = B
C.right = D

F.right = G
G.right = E

def printPreoderTree(root:TreeNode):
    if root == None:
        return
    print(root.value)
    printPreoderTree(root.left)
    printPreoderTree(root.right)

def printInoderTree(root:TreeNode):
    if root == None:
        return
    printInoderTree(root.left)
    print(root.value)
    printInoderTree(root.right)

def printAfteroderTree(root:TreeNode):
    if root == None:
        return
    printAfteroderTree(root.left)
    printAfteroderTree(root.right)
    print(root.value)


# 前序
print("-----前序-----")
printPreoderTree(A)
# 中序
print("-----中序-----")
printInoderTree(A)
# 后序
print("-----后序-----")
printAfteroderTree(A)

打印结果

-----前序-----
A
C
B
D
F
G
E
-----中序-----
B
C
D
A
F
G
E
-----后序-----
B
D
C
E
G
F
A