DLR–前序遍历(根在前,从左往右,一棵树的根永远在左子树前面,左子树又永远在右子树前面 )
LDR–中序遍历(根在中,从左往右,一棵树的左子树永远在根前面,根永远在右子树前面)
LRD–后序遍历(根在后,从左往右,一棵树的左子树永远在右子树前面,右子树永远在根前面)
from collections import dequeclass BiTreeNode:def __init__(self, data):self.data = dataself.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 = froot = 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)pre_order(root)
print("")
in_order(root)
print("")
post_order(root)
print("")
level_order(root)
结果
e,a,c,b,d,g,f,
a,b,c,d,e,g,f,
b,d,c,a,f,g,e,
e,a,g,c,f,b,d,