python实现二叉树
来源:互联网 发布:蓝牙兼容软件 编辑:程序博客网 时间:2024/06/05 11:55
这里我用python实现简单的二叉树,我实现的树在插入时会将原来的子树下降一阶
#-*- coding:utf-8 -*-#嵌套实现树#以r为根生成二叉树def newTree(r): return [r,[],[]]def getRootVal(r): return r[0]def setRootVal(r,newVal): r[0] = newValdef getLeftChild(r): return r[1]def getRightChild(r): return r[2]def insertLeftChild(r,newBranch): t = r.pop(1) if len(t)>0: root.insert(1,[newBranch,t,[]]) else: root.insert(1,[newBranch,[],[]])def insertRightChild(r,newBranch): t = r.pop(2) if len(t)>0: root.insert(2,[newBranch,[],t]) else: root.insert(2,[newBranch,[],[]])root = newTree(5)setRootVal(root,6)print rootinsertLeftChild(root,5)insertRightChild(root,7)print rootinsertLeftChild(root,4)insertRightChild(root,8)print root#类实现二叉树class newTrees: #初始化,即构造方法 def __init__(self,root): self.root = root self.leftChild = None self.rightChild = None #获取根值 def getRootVal(self): return self.root #设置根值 def setRootVal(self,newBranch): self.root = newBranch #获取左子树 def getLeft(self): return self.leftChild #获取右子树 def getRight(self): return self.rightChild #插入左子树 def insertLeft(self,newBranch): if self.leftChild == None: self.leftChild = newTrees(newBranch) else: t = newTrees(newBranch) t.leftChild = self.leftChild self.leftChild = t #插入右子树 def inserRight(self,newBranch): if self.rightChild == None: self.rightChild = newTrees(newBranch) else: t = newTrees(newBranch) t.rightChild = self.rightChild self.rightChild = t #先序遍历 def preorder(self): print(self.root) if self.leftChild: self.leftChild.preorder() if self.rightChild: self.rightChild.preorder() #中序遍历 def inoder(self): if self.leftChild: self.leftChild.inoder() print self.root if self.rightChild: self.rightChild.inoder() #后序遍历 def postorder(self): if self.leftChild: self.leftChild.postorder() if self.rightChild: self.rightChild.postorder() print self.rootroot2 = newTrees(6)root2.insertLeft(5)root2.inserRight(7)root2.insertLeft(4)root2.inserRight(8)print u'先序遍历'root2.preorder()print u'中序遍历'root2.inoder()print u'后序遍历'root2.postorder()
结果
阅读全文
0 0
- Python实现二叉树
- python实现二叉树
- python实现二叉树
- Python实现二叉树
- Python实现二叉树
- Python实现二叉树
- python实现二叉树
- Python实现二叉树
- 二叉查找树:Python实现
- python实现二叉查找树
- 二叉查找树python实现
- python实现二叉树遍历
- python实现二叉查找树
- 二叉树的实现 Python
- 二叉查找树python实现
- 二叉搜索树 python实现
- python实现二叉树排序
- python实现二叉树,以及二叉树的遍历
- 高版本windows连接低版本windows共享打印机问题
- NanoPC-T2 支持USB Audio
- HDU
- 中缀表达式转为后缀表达式(利用顺序栈实现)
- SQLServer存储过程举例简介
- python实现二叉树
- centos7安装mysql
- SQL中的distinct
- 实现APP中树形分类
- pycharm 常用功能
- Golang 优化之路——临时对象池
- Android手机客户端测试体系
- 本人某浪博客闭幕公告
- 【模板】最小生成树