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 相关文章推荐
python3图片转换二进制存入mysql
Dec 06 Python
简单的编程0基础下Python入门指引
Apr 01 Python
Python编程中字符串和列表的基本知识讲解
Oct 14 Python
日常整理python执行系统命令的常见方法(全)
Oct 22 Python
对pycharm代码整体左移和右移缩进快捷键的介绍
Jul 16 Python
Python常见MongoDB数据库操作实例总结
Jul 24 Python
Django框架实现的分页demo示例
May 25 Python
anaconda如何查看并管理python环境
Jul 05 Python
详解字符串在Python内部是如何省内存的
Feb 03 Python
使用Puppeteer爬取微信文章的实现
Feb 11 Python
Python 窗体(tkinter)下拉列表框(Combobox)实例
Mar 04 Python
ubuntu 安装pyqt5和卸载pyQt5的方法
Mar 24 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
探讨file_get_contents与curl效率及稳定性的分析
2013/06/06 PHP
PHP rsa加密解密使用方法
2015/04/27 PHP
php实现将Session写入数据库
2015/07/26 PHP
详解PHP 二维数组排序保持键名不变
2019/03/06 PHP
实现laravel 插入操作日志到数据库的方法
2019/10/11 PHP
JavaScript 事件记录使用说明
2009/10/20 Javascript
jquery中focus()函数实现当对象获得焦点后自动把光标移到内容最后
2013/09/29 Javascript
js 事件截取enter按键页面提交事件示例代码
2014/03/04 Javascript
javascript浏览器兼容教程之事件处理
2014/06/09 Javascript
JavaScript面试题大全(推荐)
2016/09/22 Javascript
jQuery实现圣诞节礼物传送(花式轮播)
2016/12/25 Javascript
javascript笔记之匿名函数和闭包
2017/02/06 Javascript
bootstrap的工具提示实例代码
2017/05/17 Javascript
jQuery实现广告条滚动效果
2017/08/22 jQuery
php main 与 iframe 相互通讯类(js+php同域/跨域)
2017/09/14 Javascript
vue 双向数据绑定的实现学习之监听器的实现方法
2018/11/30 Javascript
微信小程序纯文本实现@功能
2020/04/08 Javascript
vue设置默认首页的操作
2020/08/12 Javascript
VUE中鼠标滚轮使div左右滚动的方法详解
2020/12/14 Vue.js
[46:53]Secret vs Liquid 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
[02:42]岂曰无衣,与子同袍!DOTA2致敬每一位守护人
2020/02/17 DOTA
python自动zip压缩目录的方法
2015/06/28 Python
浅谈python为什么不需要三目运算符和switch
2016/06/17 Python
详解Python中的from..import绝对导入语句
2016/06/21 Python
200行自定义python异步非阻塞Web框架
2017/03/15 Python
django自带的权限管理Permission用法说明
2020/05/13 Python
django创建css文件夹的具体方法
2020/07/31 Python
施华洛世奇英国官网:SWAROVSKI英国
2017/03/13 全球购物
俄罗斯游戏商店:Buka
2020/03/01 全球购物
钳工实习自我鉴定
2013/09/19 职场文书
生物化工专业个人自荐信
2013/09/26 职场文书
应届生程序员求职信
2013/11/05 职场文书
文言文形式的学生求职信
2013/12/03 职场文书
机电工程学生自荐信范文
2013/12/07 职场文书
安全月宣传标语
2014/10/07 职场文书
计算机专业自荐信
2015/03/05 职场文书