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 获取新浪微博的最新公共微博实例分享
Jul 03 Python
python实现查找excel里某一列重复数据并且剔除后打印的方法
May 26 Python
Python多线程下载文件的方法
Jul 10 Python
Python中的条件判断语句与循环语句用法小结
Mar 21 Python
Python脚本实现12306火车票查询系统
Sep 30 Python
Django权限机制实现代码详解
Feb 05 Python
Python 变量类型详解
Oct 10 Python
python 文本单词提取和词频统计的实例
Dec 22 Python
Python实现html转换为pdf报告(生成pdf报告)功能示例
May 04 Python
Pandas时间序列重采样(resample)方法中closed、label的作用详解
Dec 10 Python
Python有参函数使用代码实例
Jan 06 Python
python实现贪吃蛇双人大战
Apr 18 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
德生S2000电路分析
2021/03/02 无线电
Windows中使用计划任务自动执行PHP程序实例
2014/05/09 PHP
php源码 fsockopen获取网页内容实例详解
2016/09/24 PHP
Yii2框架类自动加载机制实例分析
2018/05/02 PHP
javascript 对表格的行和列都能加亮显示
2008/12/26 Javascript
比Jquery的document.ready更快的方法
2010/04/28 Javascript
jquery 图片上传按比例预览插件集合
2011/05/28 Javascript
IE浏览器中图片onload事件无效的解决方法
2014/04/29 Javascript
JS实现在状态栏显示打字效果完整实例
2015/11/02 Javascript
JavaScript中的call和apply的用途以及区别
2017/01/11 Javascript
jQuery实现select模糊查询(反射机制)
2017/01/14 Javascript
Vue Ajax跨域请求实例详解
2017/06/20 Javascript
使用gulp构建前端自动化的方法示例
2018/12/25 Javascript
微信小程序的引导页实现代码
2020/06/24 Javascript
vue项目配置 webpack-obfuscator 进行代码加密混淆的实现
2021/02/26 Vue.js
[06:33]3.19 DOTA2发布会 海涛、冷冷、2009见证希望
2014/03/21 DOTA
[01:00:44]DOTA2上海特级锦标赛主赛事日 - 3 败者组第三轮#1COL VS Alliance第三局
2016/03/04 DOTA
python回调函数用法实例分析
2015/05/09 Python
python实现Adapter模式实例代码
2018/02/09 Python
使用numpy和PIL进行简单的图像处理方法
2018/07/02 Python
PyQt5基本控件使用详解:单选按钮、复选框、下拉框
2019/08/05 Python
Python拆分大型CSV文件代码实例
2019/10/07 Python
在pandas中遍历DataFrame行的实现方法
2019/10/23 Python
python opencv进行图像拼接
2020/03/27 Python
结束运行python的方法
2020/06/16 Python
基于OpenCV的网络实时视频流传输的实现
2020/11/15 Python
HTML5 Canvas像素处理使用接口介绍
2012/12/02 HTML / CSS
html5用video标签流式加载的实现
2020/05/20 HTML / CSS
请介绍一下WSDL的文档结构
2013/03/17 面试题
护林防火标语
2014/06/27 职场文书
乡镇党的群众路线教育实践活动个人整改方案
2014/10/31 职场文书
2014年惩防体系建设工作总结
2014/12/01 职场文书
一年级数学下册复习计划
2015/01/17 职场文书
失职检讨书大全
2015/01/26 职场文书
2015年端午节国旗下演讲稿
2015/03/19 职场文书
MySQL面试题讲解之如何设置Hash索引
2021/11/01 MySQL