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.root = BTNode()
self.queue = [] # 用于存放正在操作的子树的三个节点,依次是root, left, right
def add(self, ele):
new_node = BTNode(ele)
self.queue.append(new_node)
if self.root.key is None:
self.root = new_node
else:
tree_node = self.queue[0]
if tree_node.lchild is None:
tree_node.lchild = new_node
else:
tree_node.rchild = new_node
self.queue.pop(0)
def preOrderTrave(self, bt):
if bt is not None:
print(bt.key, end=" ")
self.preOrderTrave(bt.lchild)
self.preOrderTrave(bt.rchild)
def levelTrave(self, bt):
if bt is not None:
queue =[bt]
level = 0
while queue:
print(level, "层:", end=":")
for i in range(len(queue)):
bt = queue.pop(0)
print(bt.key, end=" ")
if bt.lchild != None:
queue.append(bt.lchild)
if bt.rchild != None:
queue.append(bt.rchild)
level = level + 1
print("\n")
btree = BiTree(data_list)
for i in range(20):
btree.add(i)
btree.preOrderTrave(btree.root)
print("\n")
btree.levelTrave(btree.root)