# 1.简单版
# 二叉树的搜索也可以分DFS和BFS 分别可以用栈和队列实现,也可以递归实现
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):
q = deque()
q.append(root)
while len(q) > 0:
node = q.popleft()
print(node.data, end='')
if node.lchild:
q.append(node.lchild)
if node.rchild:
q.append(node.rchild)
level_order(root)
# 2.升级版
class BTNode(object):
def __init__(self, key=None, lchild=None, rchild=None):
self.key = key
self.lchild = lchild
self.rchild = rchild
class BiTree(object):
def __init__(self, data_list):
# 初始化即将传入的列表的迭代器
self.it = iter(data_list)
def createBiTree(self, bt=None):
try:
# 步进获取下一个元素
next_data = next(self.it)
# 如果当前列表元素为'#', 则认为其为 None
if next_data is "#":
bt = None
else:
bt = BTNode(next_data)
bt.lchild = self.createBiTree(bt.lchild)
bt.rchild = self.createBiTree(bt.rchild)
except Exception as e:
print(e)
return bt
# 先序遍历函数
def preOrderTrave(self, bt):
if bt is not None:
print(bt.key, end=" ")
self.preOrderTrave(bt.lchild)
self.preOrderTrave(bt.rchild)
# 中序遍历函数
def inOrderTrave(self, bt):
if bt is not None:
self.inOrderTrave(bt.lchild)
print(bt.key, end=" ")
self.inOrderTrave(bt.rchild)
# 后序遍历函数
def postOrderTrave(self, bt):
if bt is not None:
self.postOrderTrave(bt.lchild)
self.postOrderTrave(bt.rchild)
print(bt.key, end=" ")
# 综合打印
def printTrave(self, bt):
print("先序遍历: ", end="")
self.preOrderTrave(bt)
print('
')
print("中序遍历: ", end="")
self.inOrderTrave(bt)
print('
')
print("后序遍历: ", end="")
self.postOrderTrave(bt)
print('
')
data = input("Please input the node value: ")
data_list = list(data)
btree = BiTree(data_list)
root = btree.createBiTree()
btree.printTrave(root)
# Please input the node value: abd#g###ce##fh###
# 先序遍历: a b d g c e f h
#
# 中序遍历: d g b a e c h f
#
# 后序遍历: g d b e h f c a