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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/nanyang1024/article/details/79983066

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

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


def add_to_tree(self, item):
'''往树里边添加节点'''
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()
tree.add_to_tree(5)
tree.add_to_tree(6)
tree.add_to_tree(7)
tree.add_to_tree(8)
tree.add_to_tree(9)
tree.add_to_tree(10) 

 

 

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

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

def add_to_tree(self, item):
'''往树里边添加节点'''
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())
    tree.add_to_tree(1)
    tree.add_to_tree(2)
    tree.add_to_tree(3)
    tree.add_to_tree(4)
    tree.add_to_tree(5)
    tree.add_to_tree(6)
    tree.add_to_tree(7)
    print(tree.is_empty())
    DFS(tree.root)
    GFS(tree.root)
  

展开阅读全文

没有更多推荐了,返回首页