# 二叉树的实现及二叉树的深度、广度遍历

#  [方法一：]二叉树的实现

class Node:
'''定义节点类型'''
def __init__(self, item):
'''初始化节点类'''
self.elem = item
self.lchild = None
self.rchild = None

class BinTree:
'''定义二叉树类'''
def __init__(self, root=None):
# 初始化一颗空树
self.root = root

'''往树里边添加节点'''
node = Node(item)
if self.root is None:
self.root = node
print('根: ',self.root.elem)
else:
# 作为缓冲
q = [self.root]
# 缓冲区不为空
while True:
# 将当前缓冲区的节点弹出
cur_node = q.pop(0)
# 判断左子树空
if cur_node.lchild is None:
cur_node.lchild = node
print('左: ', cur_node.lchild.elem)
return
# 判断右子树空
elif cur_node.rchild is None:
cur_node.rchild = node
print('右: ', cur_node.rchild.elem)
return
else:
q.append(cur_node.lchild)
q.append(cur_node.rchild)

if __name__ == '__main__':
# 测试代码
tree = BinTree()

#  [方法二：]二叉树的实现

class Node:

'''定义节点类型'''
def __init__(self, elem):
'''初始化节点类'''
self.elem = elem
self.lchild = None
self.rchild = None

class BinTree:
'''定义二叉树类'''
def __init__(self, root=None):
# 初始化一颗空树
self.root = root

def is_empty(self):
'''判断是否为空树'''
return self.root == None

'''往树里边添加节点'''
node = Node(item)
if self.is_empty():
self.root = node
print('根: ',self.root.elem)
else:
# 作为缓冲
q = [self.root]
# 缓冲区不为空
while q:
# 将当前缓冲区的节点弹出
cur_node = q.pop(0)
# 判断左子树空
if cur_node.lchild is None:
cur_node.lchild = node
print('左: ', cur_node.lchild.elem)
return self
# 判断右子树是否空
elif cur_node.rchild is None:
cur_node.rchild = node
print('右:', cur_node.rchild.elem)
return
else:
q.append(cur_node.lchild)
q.append(cur_node.rchild)

def DFS(root):
'''深度遍历'''
if root.elem is None:
return
# 先序
# print(root.elem, end=' ')
if root.lchild:
DFS(root.lchild)
# 中序
# print(root.elem, end=' ')
if root.rchild:
DFS(root.rchild)
# 后序
# print(root.elem, end=' ')

def GFS(root):
'''广度遍历'''
if root.elem is None:
return
q = [root]
while q:
cur_code = q.pop(0)
print(cur_code.elem, end=' ')
if cur_code.lchild:
q.append(cur_code.lchild)
if cur_code.rchild:
q.append(cur_code.rchild)

if __name__ == '__main__':
tree = BinTree()
print(tree.is_empty())