鱼C论坛

 找回密码
 立即注册
查看: 2205|回复: 3

[已解决]python 二叉树,广度遍历没有输出结果,敢问大神什么原因

[复制链接]
发表于 2020-2-9 18:29:34 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 翰飞gs 于 2020-2-9 18:31 编辑
  1. class Node(object):
  2.     """节点类"""
  3.     def __init__(self, item):
  4.         self.item = item
  5.         self.lchild = None
  6.         self.rchild = None


  7. class Tree(object):
  8.     """二叉树"""
  9.     def __init__(self):
  10.         self.root = None

  11.     def add(self, item):
  12.         # 为树添加节点
  13.         node = Node(item)
  14.         # 如果树是空的,对根节点赋值
  15.         if self.root is None:
  16.             self.root = node
  17.             return
  18.         # 对已有节点进行层次遍历
  19.         queue = [self.root]
  20.         # 只要队列不为空
  21.         while queue:
  22.             # 弹出队列的第一个元素
  23.             cur_node = queue.pop(0)
  24.             # 如果左节点为空,赋值;不为空,把左节点加入队列
  25.             if cur_node.lchild is None:
  26.                 cur_node.lchild = node
  27.                 return
  28.             else:
  29.                 queue.append(cur_node.lchild)
  30.             if cur_node.rchild is None:
  31.                 cur_node.rchild = node
  32.                 return
  33.             else:
  34.                 queue.append(cur_node.rchild)

  35.     def breadth_travel(self):
  36.         """广度遍历"""
  37.         if self.root is None:
  38.             return
  39.         queue = [self.root]
  40.         while queue:
  41.             cur_node = queue.pop(0)
  42.             print(cur_node.item)
  43.             if cur_node.lchild is not None:
  44.                 queue.append(cur_node.lchild)
  45.             if cur_node.rchild is not None:
  46.                 queue.append(cur_node.rchild)


  47. if __name__ is "__main__":
  48.     tree = Tree()
  49.     tree.add(1)
  50.     tree.add(2)
  51.     tree.add(3)
  52.     tree.add(4)
  53.     tree.add(5)
  54.     tree.breadth_travel()
复制代码


最佳答案
2020-2-9 18:56:51
if __name__ == "__main__":
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-2-9 18:31:36 | 显示全部楼层
广度遍历不输出结果
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-2-9 18:56:51 | 显示全部楼层    本楼为最佳答案   
if __name__ == "__main__":
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-2-9 19:03:04 | 显示全部楼层
塔利班 发表于 2020-2-9 18:56
if __name__ == "__main__":

嗯嗯嗯,这里打错了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-3-3 18:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表