标签:break class bre lan lang python travel rtt 队列
根节点
左右叶子节点
子树:
结论:
深度遍历 -- 纵向遍历,是根据根节点的位置
前序:根左右
中序:左根右
后序:左右根
实现一个二叉树:
class Node():
# 初始化一个空节点
def __init__(self,item):
self.item = item
self.left = None
self.right = None
class Tree():
# 初始化一棵空树
def __init__(self):
self.root = None
def add(self,item):
# 向空树中插入第一个节点
if self.root == None:
node = Node(item)
self.root = node
node = Node(item)
cur = self.root
queue = [cur]
while queue:
root = queue.pop(0)
if root.left != None:
# 如果左节点不为空,添加到队列
queue.append(root.left)
else:
root.left = node # 为空,添加到左节点
break
if root.right != None:
# 如果左节点不为空,添加到队列
queue.append(root.right)
else:
root.right = node
break
def travel(self):
# 广度遍历
cur = self.root
queue = [cur]
if self.root == None:
return
while queue:
root = queue.pop(0)
print(root.item)
if root.left != None:
queue.append(root.left)
if root.right != None:
queue.append(root.right)
# 深度遍历
def forward(self,root): # 前序
if root == None:
return
print(root.item)
self.forward(root.left)
self.forward(root.right)
def middle(self,root): # 中序
if root == None:
return
self.middle(root.left)
print(root.item)
self.middle(root.right)
def back(self,root): # 后序
if root == None:
return
self.back(root.left)
self.back(root.right)
print(root.item)
tree = Tree()
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)
# tree.forward(tree.root)
tree.middle(tree.root)
# tree.back(tree.root)
class sortTree():
def __init__(self):
self.root = None
def add(self,item):
node = Node(item)
cur = self.root
if self.root == None:
self.root = node
return
while 1:
if node.item < cur.item: # cur 是在变化
if cur.left == None:
cur.left = node
return
else:
cur = cur.left
else:
if cur.right == None:
cur.right = node
return
else:
cur = cur.right
def middle(self,root): # 中序
if root == None:
return
self.middle(root.left)
print(root.item)
self.middle(root.right)
tree = sortTree()
alist = [3,8,5,1,2,6,7,4]
for i in alist:
tree.add(i)
tree.middle(tree.root)
"""
1
2
3
4
5
6
7
8
"""
标签:break class bre lan lang python travel rtt 队列
原文地址:https://www.cnblogs.com/yzm1017/p/12594193.html