树--python
来源:互联网 发布:长者是谁 知乎 编辑:程序博客网 时间:2024/05/20 02:25
# coding=utf-8class node(object): def __init__(self,data=None,left=None,right=None): self.data=data self.left=left self.right=right #深度def depth(tree): if tree==None: return 0 left,right=depth(tree.left),depth(tree.right) return max(left,right)+1 #前序遍历,先遍历根节点def pre_order(tree): if tree==None: return print(tree.data) pre_order(tree.left) pre_order(tree.right) #中序遍历def mid_order(tree): if tree==None: return mid_order(tree.left) print(tree.data) mid_order(tree.right) #后序遍历def post_order(tree): if tree==None: return post_order(tree.left) post_order(tree.right) print(tree.data)#层次遍历def level_order(tree): if tree==None: return q=[] q.append(tree) while q: current=q.pop(0) print(current.data) if current.left!=None: q.append(current.left) if current.right!=None: q.append(current.right)#判断是否平衡二叉树def isbalance(tree): if tree==None: return True left,right=depth(tree.left),depth(tree.right) diff=left-right if diff<-1 or diff>1: return False return isbalance(tree.left)and isbalance(tree.right)if __name__ == '__main__': tree=node('d',node('b',node('a'),node('c')),node('e',right=node('g',node('f')))) print('前序遍历:') pre_order(tree) print('中序遍历:') mid_order(tree) print('后序遍历:') post_order(tree) print('层次遍历:') level_order(tree) print('深度:%d'%depth(tree)) print('是否为平衡二叉树:%s'%isbalance(tree))
阅读全文
0 0
- 树--python
- Python遍历文件树
- Python 二叉树练习
- Python实现二叉树
- python 二叉查找树
- python实现二叉树
- Python 线段树
- python实现二叉树
- 字典树 python实现
- python 二叉树
- 数据结构---树(Python)
- Python 遍历二叉树
- python实现目录树
- python 二叉树
- python版线段树
- Trie树python实现
- python 水仙花树
- Python目录树
- 在QT学习过程中要感谢的人
- 日常问题记录
- iOS10.1.1越狱插件推荐——SSHIcon
- 五大常用算法之四:回溯法
- js设计模式-- 装饰着模式
- 树--python
- 日志mdc
- php 常量及数据类型
- ArrayList、Vector、LinkedList的区别及其优缺点?
- solr之空间搜索剖析
- 一分钟了解"英语表达:观点/视角"
- 欢迎使用CSDN-markdown编辑器
- 关于多线程处理数据并发问题处理
- chapter12_2图片的通道分离与合并