python数据结构之二叉树的统计与转换实例_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

-------------------------

'''

时间: 2024-11-29 08:30:01

python数据结构之二叉树的统计与转换实例_python的相关文章

python实现的二叉树算法和kmp算法实例_python

主要是:前序遍历.中序遍历.后序遍历.层级遍历.非递归前序遍历.非递归中序遍历.非递归后序遍历 复制代码 代码如下: #!/usr/bin/env python#-*- coding:utf8 -*- class TreeNode(object):    def __init__(self, data=None, left=None, right=None):        self.data = data        self.left = left        self.right =

python计算书页码的统计数字问题实例_python

本文实例讲述了python计算书页码的统计数字问题,是Python程序设计中一个比较典型的应用实例.分享给大家供大家参考.具体如下: 问题描述:对给定页码n,计算出全部页码中分别用到多少次数字0,1,2,3,4...,9 实例代码如下: def count_num1(page_num): num_zero = 0 num_one = 0 num_two = 0 num_three = 0 num_four = 0 num_five = 0 num_six = 0 num_seven = 0 nu

Python中的二叉树查找算法模块使用指南_python

python中的二叉树模块内容: BinaryTree:非平衡二叉树  AVLTree:平衡的AVL树  RBTree:平衡的红黑树 以上是用python写的,相面的模块是用c写的,并且可以做为Cython的包. FastBinaryTree  FastAVLTree  FastRBTree 特别需要说明的是:树往往要比python内置的dict类慢一些,但是它中的所有数据都是按照某个关键词进行排序的,故在某些情况下是必须使用的. 安装和使用 安装方法 安装环境: ubuntu12.04, py

python数据结构之二叉树的遍历实例_python

遍历方案   从二叉树的递归定义可知,一棵非空的二叉树由根结点及左.右子树这三个基本部分组成.因此,在任一给定结点上,可以按某种次序执行三个操作:   1).访问结点本身(N)   2).遍历该结点的左子树(L)   3).遍历该结点的右子树(R) 有次序:   NLR.LNR.LRN 遍历的命名    根据访问结点操作发生位置命名:NLR:前序遍历(PreorderTraversal亦称(先序遍历))  --访问结点的操作发生在遍历其左右子树之前.LNR:中序遍历(InorderTravers

python数据结构之二叉树的建立实例_python

先建立二叉树节点,有一个data数据域,left,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 复制代码 代码如下:

Python中字典和JSON互转操作实例_python

JSON是一种轻量级的数据交换格式,各种语言都有良好的支持.字典是Python的一种数据结构.可以看成关联数组. 有些时候我们需要设计到字典转换成JSON序列化到文件,或者从文件中读取JSON.简单备忘一下. Dict转JSON写入文件 复制代码 代码如下: #!/usr/bin/env python # coding=utf-8 import json d = {'first': 'One', 'second':2} json.dump(d, open('/tmp/result.txt', '

Python实现的几个常用排序算法实例_python

前段时间为准备百度面试恶补的东西,虽然最后还是被刷了,还是把那几天的"战利品"放点上来,算法一直是自己比较薄弱的地方,以后还要更加努力啊. 下面用Python实现了几个常用的排序,如快速排序,选择排序,以及二路并归排序等等. 复制代码 代码如下: #encoding=utf-8import randomfrom copy import copy def directInsertSort(seq): """ 直接插入排序 """

python命令行参数解析OptionParser类用法实例_python

本文实例讲述了python命令行参数解析OptionParser类的用法,分享给大家供大家参考. 具体代码如下: from optparse import OptionParser parser = OptionParser(usage="usage:%prog [optinos] filepath") parser.add_option("-t", "--timeout", action = "store", type =

python基于queue和threading实现多线程下载实例_python

本文实例讲述了python基于queue和threading实现多线程下载的方法,分享给大家供大家参考.具体方法如下: 主代码如下: #download worker queue_download = Queue.Queue(0) DOWNLOAD_WORKERS = 20 for i in range(DOWNLOAD_WORKERS): DownloadWorker(queue_download).start() #start a download worker for md5 in MD5