python——二叉树的层次遍历
来源:互联网 发布:修改虚拟网卡mac地址 编辑:程序博客网 时间:2024/06/05 18:36
class Node: def __init__(self,data,left=None,right=None): self.data=data self.left=left self.right=right #层次遍历 def lookup(self): queue = [self] l=[] while queue: current = queue.pop(0) l.append(current.data) if current.left: queue.append(current.left) if current.right: queue.append(current.right) return l #分层打印树 def printLevel(self): currentLevel=[self] val=[] while currentLevel: val.append([c.data for c in currentLevel]) nextLevel=[] for i in currentLevel: if i.left: nextLevel.append(i.left) if i.right: nextLevel.append(i.right) currentLevel=nextLevel return val def __str__(self): s=self.printLevel() return '%s'%stree=Node(0, Node(1, Node(3, Node(7), Node(8)), Node(4, Node(9), Node(10))), Node(2, Node(5, Node(11), Node(12)), Node(6, Node(13), Node(14))) )tree2=Node(0, Node(1, Node(3, Node(7), Node(8)), ), Node(2, Node(5, Node(11), Node(12)), Node(6)) )print(tree.deep())print(tree2)#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]#[[0], [1, 2], [3, 5, 6], [7, 8, 11, 12]]
阅读全文
0 0
- python——二叉树的层次遍历
- python二叉树的层次遍历
- 二叉树的遍历(前中后,层次)——legend
- 数据结构——二叉树的层次遍历
- 数据结构例程——二叉树的层次遍历算法
- lintcode——二叉树的层次遍历
- 层次遍历二叉树—vector的彪悍与神秘
- 数据结构 — 5.二叉树层次遍历
- 数据结构—二叉树层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 数学笔记15——微积分第二基本定理
- SQL注入之联合查询注入
- mysql innobackupex 备份问题
- poj3176动归
- JMM概述
- python——二叉树的层次遍历
- input的onChange、router、table文本超出隐藏(阶段记录)
- 一个人的旅行
- 数串
- windows和Linux下安装imagick扩展(linux下支持pdf转image)
- Android开发中更新UI的几种常用方式
- 使用easymock做单元测试
- 使用npm安装electron时卡在install.js的解决办法
- 内部类