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


Posted in Python onApril 25, 2014

主要是:前序遍历、中序遍历、后序遍历、层级遍历、非递归前序遍历、非递归中序遍历、非递归后序遍历

#!/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 = right

class Tree(object):
    def __init__(self, root=None):
        self.root = None
    def makeTree(self, data, left, right):
        self.root = TreeNode(data, left, right)
    def is_empty(self):
        """是否为空 """
        if self.root is None:
            return True
        return False
    def preOrder(self, r):
        """前序遍历 """
        if not r.is_empty():
            print r.root.data
            if r.root.left is not None:
                r.preOrder(r.root.left)
            if r.root.right is not None:
                r.preOrder(r.root.right)
    def inOrder(self, r):
        """中序遍历 """
        if not r.is_empty():
            if r.root.left is not None:
                r.preOrder(r.root.left)
            print r.root.data
            if r.root.right is not None:
                r.preOrder(r.root.right)
    def postOrder(self, r):
        """后续遍历 """
        if not r.is_empty():
            if r.root.left is not None:
                r.preOrder(r.root.left)
            print r.root.data
            if r.root.right is not None:
                r.preOrder(r.root.right)
    def levelOrder(self, r):
        """层级遍历 """
        if not r.is_empty():
            s = [r]
            while len(s) > 0:
                temp = s.pop(0)  # 先弹出最先append到的点
                if temp and temp.root is not None:
                    print temp.root.data
                    if temp.root.left is not None:
                        s.append(temp.root.left)
                    if self.root.right is not None:
                        s.append(temp.root.right)
    def preOrder1(self, r):
        """非递归 前序遍历 """
        stack = []
        current = r
        while len(stack) > 0 or (current and not current.is_empty()):
            while current and not current.is_empty():
                print current.root.data
                stack.append(current)
                current = current.root.left
            if len(stack) > 0:
                current = stack.pop()
                current = current.root.right
    def inOrder1(self, r):
        """非递归 中序遍历 """
        stack = []
        current = r
        while len(stack) > 0 or (current and not current.is_empty()):
            while current and not current.is_empty():
                stack.append(current)
                current = current.root.left
            if len(stack) > 0:
                current = stack.pop()
                print current.root.data
                current = current.root.right
    def postOrder1(self, r):
        """非递归 后续遍历 """
        stack = []
        current = r
        pre = None
        while len(stack) > 0 or (current and not current.is_empty()):
            if current and not current.is_empty():
                stack.append(current)
                current = current.root.left
            elif stack[-1].root.right != pre:
                current = stack[-1].root.right
                pre = None
            else:
                pre = stack.pop()
                print pre.root.data
    def leaves_count(self, r):
        """求叶子节点个数 """
        if r.is_empty():
            return 0
        elif (not r.root.left) and (not r.root.right):
            return 1
        else:
            return r.root.left.leaves_count(r.root.left) + r.root.right.leaves_count(r.root.right)

if __name__ == '__main__':
    """二叉树"""
    ra, rb, rc, rd, re, rf = Tree(), Tree(), Tree(), Tree(), Tree(), Tree()
    ra.makeTree("a", None, None)
    rb.makeTree("b", None, None)
    rc.makeTree("c", None, None)
    rd.makeTree("d", None, None)
    re.makeTree("e", None, None)
    rf.makeTree("f", None, None)
    r1, r2, r3, r4, r = Tree(), Tree(), Tree(), Tree(), Tree()
    r1.makeTree("-", rc, rd)
    r2.makeTree("*", rb, r1)
    r3.makeTree("+", ra, r2)
    r4.makeTree("/", re, rf)
    r.makeTree("-", r3, r4)
    r.preOrder(r)
    r.inOrder(r)
    r.postOrder(r)
    r.levelOrder(r)
    print r.leaves_count(r)

大学的时候学过kmp算法,最近在看的时候发现竟然忘了,所以去重新看了看书,然后用python写下了这个算法:

def kmp(text, pattern):
    """kmp算法 """
    pattern = list(pattern)
    next = [-1] * len(pattern)
    #next 函数
    i, j = 1, -1
    for i in range(1, len(pattern)):
        j = next[i - 1]
        while True:
            if pattern[i - 1] == pattern[j] or j == -1:
                next[i] = j + 1
                break
            else:
                j = next[j]
    #循环比较
    i, j = 0, 0
    while i < len(text) and j < len(pattern):
        if text[i] == pattern[j] or j == -1:
            i += 1
            j += 1
        else:
            j = next[j]
    #返回结果 如果匹配,返回匹配的位置,否则返回-1
    if j == len(pattern):
        print i ? j
    else:
        print -1
Python 相关文章推荐
Python列表(list)、字典(dict)、字符串(string)基本操作小结
Nov 28 Python
Python2.x版本中基本的中文编码问题解决
Oct 12 Python
python字符类型的一些方法小结
May 16 Python
Python模拟登陆实现代码
Jun 14 Python
在PyCharm环境中使用Jupyter Notebook的两种方法总结
May 24 Python
使用python对excle和json互相转换的示例
Oct 23 Python
Python pandas实现excel工作表合并功能详解
Aug 29 Python
python基于gevent实现并发下载器代码实例
Nov 01 Python
深入理解Tensorflow中的masking和padding
Feb 24 Python
Python range与enumerate函数区别解析
Feb 28 Python
Python 如何反方向迭代一个序列
Jul 28 Python
详解pytorch创建tensor函数
Mar 22 Python
python中的__init__ 、__new__、__call__小结
Apr 25 #Python
Python yield 小结和实例
Apr 25 #Python
python计数排序和基数排序算法实例
Apr 25 #Python
python处理圆角图片、圆形图片的例子
Apr 25 #Python
python实现的阳历转阴历(农历)算法
Apr 25 #Python
Python实现的简单万年历例子分享
Apr 25 #Python
python实现simhash算法实例
Apr 25 #Python
You might like
全国FM电台频率大全 - 31 新疆维吾尔族自治区
2020/03/11 无线电
Mysql的常用命令
2006/10/09 PHP
基于php和mysql的简单的dao类实现crud操作功能
2014/01/27 PHP
PHP读取大文件的几种方法介绍
2016/10/27 PHP
phpStudy2016 配置多个域名期间遇到的问题小结
2017/10/19 PHP
PHP用函数嵌入网站访问量计数器
2017/10/27 PHP
PHP面向对象程序设计之接口的继承定义与用法详解
2018/12/20 PHP
PHP中-&gt;和=&gt;的含义及使用示例解析
2020/08/06 PHP
Javascript valueOf 使用方法
2008/12/28 Javascript
event.currentTarget与event.target的区别介绍
2012/12/31 Javascript
jquery列表拖动排列(由项目提取相当好用)
2014/06/17 Javascript
JavaScript制作简易的微信打飞机
2015/03/31 Javascript
Yii2使用Bootbox插件实现自定义弹窗
2015/04/02 Javascript
基于JS实现checkbox全选功能实例代码
2016/10/31 Javascript
JS ES6中setTimeout函数的执行上下文示例
2017/04/27 Javascript
微信小程序使用map组件实现路线规划功能示例
2019/01/22 Javascript
微信小程序自定义可滑动顶部TabBar选项卡实现页面切换功能示例
2019/05/14 Javascript
PyMongo安装使用笔记
2015/04/27 Python
Python中Class类用法实例分析
2015/11/12 Python
NetworkX之Prim算法(实例讲解)
2017/12/22 Python
python 用lambda函数替换for循环的方法
2018/06/09 Python
在NumPy中创建空数组/矩阵的方法
2018/06/15 Python
Python实现计算字符串中出现次数最多的字符示例
2019/01/21 Python
python使用requests模块实现爬取电影天堂最新电影信息
2019/04/03 Python
python实现将视频按帧读取到自定义目录
2019/12/10 Python
Django单元测试中Fixtures用法详解
2020/02/25 Python
pandas中read_csv、rolling、expanding用法详解
2020/04/21 Python
使用CSS Grid布局实现网格的流动
2014/12/30 HTML / CSS
x-ua-compatible content=”IE=7, IE=9″意思理解
2013/07/22 HTML / CSS
使用HTML5加载音频和视频的实现代码
2020/11/30 HTML / CSS
Shoes For Crews法国官网:美国领先的防滑鞋设计和制造商
2018/01/01 全球购物
Fabletics官网:美国运动服饰品牌,由好莱坞女演员凯特·哈德森创立
2019/10/19 全球购物
职务任命书范本
2014/06/05 职场文书
2014年预备党员端正入党动机思想汇报
2014/09/13 职场文书
作风建设整改方案
2014/10/27 职场文书
英语辞职信范文
2015/02/28 职场文书