python数据结构之二叉树的统计与转换实例


Posted in Python onApril 29, 2014

一、获取二叉树的深度

就是二叉树最后的层次,如下图:

python数据结构之二叉树的统计与转换实例

实现代码:

def getheight(self):
        ''' 获取二叉树深度 '''
        return self.__get_tree_height(self.root)    def __get_tree_height(self, root):
        if root is 0:
            return 0
        if root.left is 0 and root.right is 0:
            return 1
        else:
            left = self.__get_tree_height(root.left)
            right = self.__get_tree_height(root.right)
            if left < right:
                return right + 1
            else:
                return left + 1

二、叶子的统计

叶子就是二叉树的节点的 left 指针和 right 指针分别指向空的节点

def getleafcount(self):
        ''' 获取二叉树叶子数 '''
        return self.__count_leaf_node(self.root)    def __count_leaf_node(self, root):
        res = 0
        if root is 0:
            return res
        if root.left is 0 and root.right is 0:
            res += 1
            return res
        if root.left is not 0:
            res += self.__count_leaf_node(root.left)
        if root.right is not 0:
            res += self.__count_leaf_node(root.right)
        return res

三、统计叶子的分支节点

与叶子节点相对的其他节点 left 和 right 的指针指向其他节点

def getbranchcount(self):
        ''' 获取二叉树分支节点数 '''
        return self.__get_branch_node(self.root)    def __get_branch_node(self, root):
        if root is 0:
            return 0
        if root.left is 0 and root.right is 0:
            return 0
        else:
            return 1 + self.__get_branch_node(root.left) + self.__get_branch_node(root.right)

四、二叉树左右树互换

def replacelem(self):
        ''' 二叉树所有结点的左右子树相互交换 '''
        self.__replace_element(self.root)    def __replace_element(self, root):
        if root is 0:
            return
        root.left, root.right = root.right, root.left
        self.__replace_element(root.left)
        self.__replace_element(root.right)

这些方法和操作,都是运用递归。其实二叉树的定义也是一种递归。附上最后的完整代码:

# -*- coding: utf - 8 - *-    
class TreeNode(object):
    def __init__(self, left=0, right=0, data=0):
        self.left = left
        self.right = right
        self.data = data
    
class BinaryTree(object):
    def __init__(self, root=0):
        self.root = root
    def is_empty(self):
        if self.root is 0:
            return True
        else:
            return False
    def create(self):
        temp = input('enter a value:')
        if temp is '#':
            return 0
        treenode = TreeNode(data=temp)
        if self.root is 0:
            self.root = treenode
        treenode.left = self.create()
        treenode.right = self.create()
    def preorder(self, treenode):
        '前序(pre-order,NLR)遍历'
        if treenode is 0:
            return
        print treenode.data
        self.preorder(treenode.left)
        self.preorder(treenode.right)
    def inorder(self, treenode):
        '中序(in-order,LNR'
        if treenode is 0:
            return
        self.inorder(treenode.left)
        print treenode.data
        self.inorder(treenode.right)
    def postorder(self, treenode):
        '后序(post-order,LRN)遍历'
        if treenode is 0:
            return
        self.postorder(treenode.left)
        self.postorder(treenode.right)
        print treenode.data
    def preorders(self, treenode):
        '前序(pre-order,NLR)非递归遍历'
        stack = []
        while treenode or stack:
            if treenode is not 0:
                print treenode.data
                stack.append(treenode)
                treenode = treenode.left
            else:
                treenode = stack.pop()
                treenode = treenode.right
    def inorders(self, treenode):
        '中序(in-order,LNR) 非递归遍历'
        stack = []
        while treenode or stack:
            if treenode:
                stack.append(treenode)
                treenode = treenode.left
            else:
                treenode = stack.pop()
                print treenode.data
                treenode = treenode.right
    def postorders(self, treenode):
        '后序(post-order,LRN)非递归遍历'
        stack = []
        pre = 0
        while treenode or stack:
            if treenode:
                stack.append(treenode)
                treenode = treenode.left
            elif stack[-1].right != pre:
                treenode = stack[-1].right
                pre = 0
            else:
                pre = stack.pop()
                print pre.data
    # def postorders(self, treenode):
    #     '后序(post-order,LRN)非递归遍历'
    #     stack = []
    #     queue = []
    #     queue.append(treenode)
    #     while queue:
    #         treenode = queue.pop()
    #         if treenode.left:
    #             queue.append(treenode.left)
    #         if treenode.right:
    #             queue.append(treenode.right)
    #         stack.append(treenode)
    #     while stack:
    #         print stack.pop().data
    def levelorders(self, treenode):
        '层序(post-order,LRN)非递归遍历'
        from collections import deque
        if not treenode:
            return
        q = deque([treenode])
        while q:
            treenode = q.popleft()
            print treenode.data
            if treenode.left:
                q.append(treenode.left)
            if treenode.right:
                q.append(treenode.right)
    def getheight(self):
        ''' 获取二叉树深度 '''
        return self.__get_tree_height(self.root)
    def __get_tree_height(self, root):
        if root is 0:
            return 0
        if root.left is 0 and root.right is 0:
            return 1
        else:
            left = self.__get_tree_height(root.left)
            right = self.__get_tree_height(root.right)
            if left < right:
                return right + 1
            else:
                return left + 1
    def getleafcount(self):
        ''' 获取二叉树叶子数 '''
        return self.__count_leaf_node(self.root)
    def __count_leaf_node(self, root):
        res = 0
        if root is 0:
            return res
        if root.left is 0 and root.right is 0:
            res += 1
            return res
        if root.left is not 0:
            res += self.__count_leaf_node(root.left)
        if root.right is not 0:
            res += self.__count_leaf_node(root.right)
        return res
    def getbranchcount(self):
        ''' 获取二叉树分支节点数 '''
        return self.__get_branch_node(self.root)
    def __get_branch_node(self, root):
        if root is 0:
            return 0
        if root.left is 0 and root.right is 0:
            return 0
        else:
            return 1 + self.__get_branch_node(root.left) + self.__get_branch_node(root.right)
    def replacelem(self):
        ''' 二叉树所有结点的左右子树相互交换 '''
        self.__replace_element(self.root)
    def __replace_element(self, root):
        if root is 0:
            return
        root.left, root.right = root.right, root.left
        self.__replace_element(root.left)
        self.__replace_element(root.right)
node1 = TreeNode(data=1)
node2 = TreeNode(node1, 0, 2)
node3 = TreeNode(data=3)
node4 = TreeNode(data=4)
node5 = TreeNode(node3, node4, 5)
node6 = TreeNode(node2, node5, 6)
node7 = TreeNode(node6, 0, 7)
node8 = TreeNode(data=8)
root = TreeNode(node7, node8, 'root')
    
bt = BinaryTree(root)
print u'''
生成的二叉树
------------------------
         root
      7        8
    6
  2   5
1    3 4
-------------------------
'''
Python 相关文章推荐
极简的Python入门指引
Apr 01 Python
python中pandas.DataFrame对行与列求和及添加新行与列示例
Mar 12 Python
Pycharm学习教程(5) Python快捷键相关设置
May 03 Python
Django验证码的生成与使用示例
May 20 Python
python pandas 组内排序、单组排序、标号的实例
Apr 12 Python
详谈pandas中agg函数和apply函数的区别
Apr 20 Python
详解python之heapq模块及排序操作
Apr 04 Python
Python倒排索引之查找包含某主题或单词的文件
Nov 13 Python
python之pymysql模块简单应用示例代码
Dec 16 Python
Windows+Anaconda3+PyTorch+PyCharm的安装教程图文详解
Apr 03 Python
python 爬虫如何正确的使用cookie
Oct 27 Python
基于python制作简易版学生信息管理系统
Apr 20 Python
python数据结构之二叉树的遍历实例
Apr 29 #Python
python数据结构之二叉树的建立实例
Apr 29 #Python
python数据结构树和二叉树简介
Apr 29 #Python
Python的ORM框架SQLAlchemy入门教程
Apr 28 #Python
Python中实现远程调用(RPC、RMI)简单例子
Apr 28 #Python
Python的ORM框架SQLObject入门实例
Apr 28 #Python
django自定义Field实现一个字段存储以逗号分隔的字符串
Apr 27 #Python
You might like
PHP+Ajax检测用户名或邮件注册时是否已经存在实例教程
2014/08/23 PHP
PHP中使用php://input处理相同name值的表单数据
2015/02/03 PHP
PHP批量获取网页中所有固定种子链接的方法
2016/11/18 PHP
thinkphp3.2嵌入百度编辑器ueditor的实例代码
2017/07/13 PHP
jQuery+jqmodal弹出窗口实现代码分明
2010/06/14 Javascript
js两种拼接字符串的简单方法(必看)
2016/09/02 Javascript
jQuery源码分析之sizzle选择器详解
2017/02/13 Javascript
form表单序列化详解(推荐)
2017/08/15 Javascript
nodeJs实现基于连接池连接mysql的方法示例
2018/02/10 NodeJs
关于Webpack dev server热加载失败的解决方法
2018/02/22 Javascript
详谈vue中router-link和传统a链接的区别
2020/07/22 Javascript
[41:12]Liquid vs Secret 2019国际邀请赛淘汰赛 败者组 BO3 第一场 8.24
2019/09/10 DOTA
Python写的创建文件夹自定义函数mkdir()
2014/08/25 Python
python爬取w3shcool的JQuery课程并且保存到本地
2017/04/06 Python
Python基于Socket实现的简单聊天程序示例
2017/08/05 Python
利用python批量修改word文件名的方法示例
2017/10/17 Python
Python中xrange与yield的用法实例分析
2017/12/26 Python
python中类的属性和方法介绍
2018/11/27 Python
对python PLT中的image和skimage处理图片方法详解
2019/01/10 Python
Python面向对象总结及类与正则表达式详解
2019/04/18 Python
详解Numpy数组转置的三种方法T、transpose、swapaxes
2019/05/27 Python
Python3+Requests+Excel完整接口自动化测试框架的实现
2019/10/11 Python
python 高阶函数简单介绍
2021/02/19 Python
使用CSS3配合IE滤镜实现渐变和投影的效果
2015/09/06 HTML / CSS
德国宠物用品、宠物食品及水族馆网上商店:ZooRoyal
2017/07/09 全球购物
Set里的元素是不能重复的,那么用什么方法来区分重复与否呢? 是用==还是equals()? 它们有何区别?用contains来区分是否有重复的对象。还是都不用
2013/07/30 面试题
中学生评语大全
2014/04/18 职场文书
银行求职信怎么写
2014/05/26 职场文书
大学生撤销处分思想汇报
2014/09/12 职场文书
工程合作意向书范本
2015/05/09 职场文书
刑事辩护词范文
2015/05/21 职场文书
2016年4月份红领巾广播稿
2015/12/21 职场文书
党校培训学习心得体会
2016/01/06 职场文书
导游词之峨眉乐山/兵马俑/北京故宫御花园
2019/09/03 职场文书
C#连接ORACLE出现乱码问题的解决方法
2021/10/05 Oracle
python标准库ElementTree处理xml
2022/05/20 Python