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中dir函数用法分析
Apr 17 Python
浅析Python中signal包的使用
Nov 13 Python
Python 装饰器使用详解
Jul 29 Python
Python:Scrapy框架中Item Pipeline组件使用详解
Dec 27 Python
Python中sort和sorted函数代码解析
Jan 25 Python
Pycharm+Scrapy安装并且初始化项目的方法
Jan 15 Python
python之生产者消费者模型实现详解
Jul 27 Python
Python Django中的STATIC_URL 设置和使用方式
Mar 27 Python
python 制作简单的音乐播放器
Nov 25 Python
使用pandas读取表格数据并进行单行数据拼接的详细教程
Mar 03 Python
解决Python中的modf()函数取小数部分不准确问题
May 28 Python
Pandas 数据编码的十种方法
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
smarty+adodb+部分自定义类的php开发模式
2006/12/31 PHP
Zend的Registry机制的使用说明
2013/05/02 PHP
joomla组件开发入门教程
2016/05/04 PHP
laravel批量生成假数据的方法
2019/10/09 PHP
js网页侧边随页面滚动广告效果实现
2011/04/14 Javascript
用js调用迅雷下载代码的二种方法
2013/04/15 Javascript
点击标签切换和自动切换DIV选项卡
2014/08/10 Javascript
js实现div弹出层的方法
2014/11/20 Javascript
JS实现双击屏幕滚动效果代码
2015/10/28 Javascript
理解javascript定时器中的setTimeout与setInterval
2016/02/23 Javascript
Boostrap基础教程之JavaScript插件篇
2016/09/08 Javascript
js中string和number类型互转换技巧(分享)
2016/11/28 Javascript
bootstrap制作jsp页面(根据值让table显示选中)
2017/01/05 Javascript
浅谈js-FCC算法Friendly Date Ranges(详解)
2017/04/10 Javascript
利用纯js + transition动画实现移动端web轮播图详解
2017/09/10 Javascript
JavaScript实现QQ列表展开收缩扩展功能
2017/10/30 Javascript
对layui初始化列表的CheckBox属性详解
2019/09/13 Javascript
[02:05:03]完美世界DOTA2联赛循环赛 LBZS VS Matador BO2 10.28
2020/10/28 DOTA
[08:56]DOTA2-DPC中国联赛2月23日Recap集锦
2021/03/11 DOTA
python文件和目录操作方法大全(含实例)
2014/03/12 Python
跟老齐学Python之复习if语句
2014/10/02 Python
python动态加载包的方法小结
2016/04/18 Python
Python一键查找iOS项目中未使用的图片、音频、视频资源
2019/08/12 Python
python实现堆排序的实例讲解
2020/02/21 Python
python语言是免费还是收费的?
2020/06/15 Python
使用K.function()调试keras操作
2020/06/17 Python
CSS3中31种选择器使用方法教程
2013/12/05 HTML / CSS
英国品牌男装折扣网站:Brown Bag
2018/03/08 全球购物
俄罗斯极限运动网上商店:Board Shop №1
2020/12/18 全球购物
环保建议书100字
2014/05/14 职场文书
投标授权委托书范文
2014/08/02 职场文书
服务员态度差检讨书
2014/10/28 职场文书
转学证明范本
2015/06/19 职场文书
迎新生晚会主持词
2015/06/30 职场文书
学生会副主席竞选稿
2015/11/19 职场文书
Python爬虫网络请求之代理服务器和动态Cookies
2022/04/12 Python