16 树
class Node(object):
def __init__(self, item):
self.item = 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.item, end=" ")
if cur_node.lchild is not None:
queue.append(cur_node.lchild)
if cur_node.rchild is not None:
queue.append(cur_node.rchild)
def pre_order(self, root):
"""先序遍历: 根 左 右"""
if root is None:
return
print(root.item, end=" ")
self.pre_order(root.lchild)
self.pre_order(root.rchild)
def in_order(self, root):
"""中序遍历: 左 根 右"""
if root is None:
return
self.in_order(root.lchild)
print(root.item, end=" ")
self.in_order(root.rchild)
def post_order(self, root):
"""后序遍历: 左 右 根"""
if root is None:
return
self.post_order(root.lchild)
self.post_order(root.rchild)
print(root.item, end=" ")