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 文件操作实现代码
Oct 07 Python
Python编程入门的一些基本知识
May 13 Python
Python爬虫抓取手机APP的传输数据
Jan 22 Python
python利用ffmpeg进行录制屏幕的方法
Jan 10 Python
python 判断矩阵中每行非零个数的方法
Jan 26 Python
python中的&amp;&amp;及||的实现示例
Aug 07 Python
python的slice notation的特殊用法详解
Dec 27 Python
python:目标检测模型预测准确度计算方式(基于IoU)
Jan 18 Python
Django 实现对已存在的model进行更改
Mar 28 Python
Python3创建Django项目的几种方法(3种)
Jun 03 Python
Numpy 多维数据数组的实现
Jun 18 Python
keras的load_model实现加载含有参数的自定义模型
Jun 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
《破坏领主》销量已超100万 未来将继续开发新内容
2020/03/08 其他游戏
php strstr查找字符串中是否包含某些字符的查找函数
2010/06/03 PHP
PHP gbk环境下json_dencode传送来的汉字
2012/11/13 PHP
PHP+shell实现多线程的方法
2015/07/01 PHP
非常经典的PHP文件上传类分享
2016/05/15 PHP
php使用ftp实现文件上传与下载功能
2017/07/21 PHP
php记录搜索引擎爬行记录的实现代码
2018/03/02 PHP
PHP实现简易用户登录系统
2020/07/10 PHP
jquery 获取json数据实现代码
2009/04/27 Javascript
JavaScript函数使用的基本教程
2015/06/04 Javascript
JS面向对象编程详解
2016/03/06 Javascript
jquery css实现邮箱自动补全
2016/11/14 Javascript
nodejs 终端打印进度条实例代码
2017/04/22 NodeJs
vue实现百度搜索下拉提示功能实例
2017/06/14 Javascript
js使用generator函数同步执行ajax任务
2017/09/05 Javascript
JS使用正则表达式获取小括号、中括号及花括号内容的方法示例
2018/06/01 Javascript
原生js基于canvas实现一个简单的前端截图工具代码实例
2019/09/10 Javascript
JS随机密码生成算法
2019/09/23 Javascript
解决layui table表单提示数据接口请求异常的问题
2019/09/24 Javascript
python教程之用py2exe将PY文件转成EXE文件
2014/06/12 Python
PyQT5 QTableView显示绑定数据的实例详解
2019/06/25 Python
tensorflow中tf.slice和tf.gather切片函数的使用
2020/01/19 Python
python 递归调用返回None的问题及解决方法
2020/03/16 Python
基于CentOS搭建Python Django环境过程解析
2020/08/24 Python
利用CSS的Sass预处理器(框架)来制作居中效果
2016/03/10 HTML / CSS
Javascript 高级手势使用介绍
2013/04/21 HTML / CSS
Marc Jacobs官方网站:美国奢侈品牌
2017/08/29 全球购物
我的珠宝盒:Ma boîte à bijoux
2019/08/27 全球购物
资产经营总监岗位职责
2013/12/04 职场文书
网络书店创业计划书
2014/02/07 职场文书
家庭困难证明
2014/10/12 职场文书
2014年行政助理工作总结
2014/11/19 职场文书
低端且暴利的线上线下创业项目分享
2019/09/03 职场文书
使用HTML+Css+transform实现3D导航栏的示例代码
2021/03/31 HTML / CSS
MySQL系列之十二 备份与恢复
2021/07/02 MySQL
mongodb清除连接和日志的正确方法分享
2021/09/15 MongoDB