树的遍历,可以广度遍历也可以深度遍历
广度遍历:一层层找
代码实现:
# coding:utf-8
# 由于树是链表的扩充,所以也要有节点类
class Node(object):
""""""
def __init__(self, item):
self.elem = item
self.lchild = None # 定义左右子节点
self.rchild = None
class Tree(object):
"""二叉树"""
def __init__(self):
self.root = None # 保存了一个根节点
def add(self, item):
"""添加元素"""
node = Node(item)
if self.root is None:
self.root = node
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
if cur_node.lchild is None:
cur_node.lchild = node
return
else:
queue.append(cur_node.lchild)
if cur_node.rchild is None:
cur_node.rchild = node
return
else:
queue.append(cur_node.rchild)
def breadth_travel(self):
"""广度遍历"""
if self.root is None:
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
print(cur_node.elem)
if cur_node.lchild is not None:
queue.append(cur_node.lchild)
if cur_node.rchild is not None:
queue.append(cur_node.rchild)
if __name__ == "__main__":
tree = Tree()
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.breadth_travel()
实现结果: