直接上代碼:
#coding:utf-8
class Node(object):
"""二叉樹節(jié)點"""
def __init__(self, item):
super(Node, self).__init__()
self.item = item
self.lchild = None
self.rchild = None
class Tree(object):
"""二叉樹類"""
def __init__(self):
super(Tree, self).__init__()
self.root = None
def add(self, item):
"""添加節(jié)點"""
node = Node(item)
# 判斷當前樹是否為空
if self.root is None:
self.root = node
else:
queue = []
queue.append(self.root)
# 采用隊列存放, 先將根節(jié)點放入隊列中,取出,看是否有左子樹和右子樹,有就放入并且循環(huán)回來看子樹的子樹,沒有則添加
while queue:
temp = queue.pop(0)
# 看做節(jié)點是否為空
if temp.lchild is None:
temp.lchild = node
break
# 看右節(jié)點是否為空
elif temp.rchild is None:
temp.rchild = node
break
# 都不為空,將左節(jié)點和右節(jié)點放入隊列
else:
queue.append(temp.lchild)
queue.append(temp.rchild)
def wide_travel(self):
"""廣度優(yōu)先遍歷(廣序遍歷):從上到下,從左到右.利用隊列"""
if self.root is None:
return
else:
queue = []
queue.append(self.root)
while queue:
temp = queue.pop(0)
print(temp.item, end=" ")
# 如果有左孩子則放入隊列
if temp.lchild is not None:
queue.append(temp.lchild)
# 如果有右孩子則放入隊列
if temp.rchild is not None:
queue.append(temp.rchild)
print()
# 深度遍歷采用了遞歸
def preorder(self, node):
"""深度遍歷-先序遍歷(根節(jié)點-左子樹-右子樹)"""
if node is None:
return
print(node.item, end=" ")
self.preorder(node.lchild)
self.preorder(node.rchild)
def inorder(self, node):
"""深度遍歷-中序遍歷(左子樹-根節(jié)點-右子樹)"""
if node is None:
return
self.inorder(node.lchild)
print(node.item, end=" ")
self.inorder(node.rchild)
def posorder(self, node):
"""深度遍歷-后序遍歷(左子樹-右子樹-根節(jié)點)"""
if node is None:
return
self.posorder(node.lchild)
self.posorder(node.rchild)
print(node.item, end=" ")
if __name__ == '__main__':
tree = Tree()
for char in "ABCDEFG":
tree.add(char)
print("先序遍歷:")
tree.preorder(tree.root)
print("\n中序遍歷:")
tree.inorder(tree.root)
print("\n后序遍歷:")
tree.posorder(tree.root)
print("\n廣度遍歷:")
tree.wide_travel()
歡迎一起分享和交流python---->q群:556993881
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者