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记录运行pid,并在需要时kill掉它们的实例
Jan 16 Python
Python三级菜单的实例
Sep 13 Python
Python通过调用mysql存储过程实现更新数据功能示例
Apr 03 Python
python实现textrank关键词提取
Jun 22 Python
python点击鼠标获取坐标(Graphics)
Aug 10 Python
Python for循环及基础用法详解
Nov 08 Python
Python中sorted()排序与字母大小写的问题
Jan 14 Python
TensorFlow通过文件名/文件夹名获取标签,并加入队列的实现
Feb 17 Python
基于Python的自媒体小助手---登录页面的实现代码
Jun 29 Python
win10安装python3.6的常见问题
Jul 01 Python
浅析Python 序列化与反序列化
Aug 05 Python
python图像处理 PIL Image操作实例
Apr 09 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
SONY SRF-M100的电路分析
2021/03/02 无线电
php-accelerator网站加速PHP缓冲的方法
2008/07/30 PHP
ajax完美实现两个网页 分页功能的实例代码
2013/04/16 PHP
php操作mongodb封装类与用法实例
2018/09/01 PHP
javascript编程起步(第五课)
2007/02/27 Javascript
Extjs列表详细信息窗口新建后自动加载解决方法
2010/04/02 Javascript
js控制文本框只输入数字和小数点的方法
2015/03/10 Javascript
JavaScript识别网页关键字并进行描红的方法
2015/11/09 Javascript
JS实现图片高亮展示效果实例
2015/11/24 Javascript
bootstrap基础知识学习笔记
2016/11/02 Javascript
基于JS实现移动端向左滑动出现删除按钮功能
2017/02/22 Javascript
JavaScript数据结构学习之数组、栈与队列
2017/05/02 Javascript
基于BootStrap的前端分页带省略号和上下页效果
2017/05/18 Javascript
微信小程序scroll-view实现滚动穿透和阻止滚动的方法
2018/08/20 Javascript
在vue项目中,将juery设置为全局变量的方法
2018/09/25 Javascript
基于nodejs的雪碧图制作工具的示例代码
2018/11/05 NodeJs
javaScript实现游戏倒计时功能
2018/11/17 Javascript
JavaScript本地储存:localStorage、sessionStorage、cookie的使用
2020/10/13 Javascript
微信小程序将页面按钮悬浮固定在底部的实现代码
2020/10/29 Javascript
VUE前端从后台请求过来的数据进行转换数据结构操作
2020/11/11 Javascript
python安装与使用redis的方法
2016/04/19 Python
Python ldap实现登录实例代码
2016/09/30 Python
详解python的数字类型变量与其方法
2016/11/20 Python
Python实现的双色球生成功能示例
2017/12/18 Python
python 解压pkl文件的方法
2018/10/25 Python
Python Request爬取seo.chinaz.com百度权重网站的查询结果过程解析
2019/08/13 Python
Python中实现一行拆多行和多行并一行的示例代码
2020/09/06 Python
CSS3用@font-face实现自定义英文字体
2013/09/23 HTML / CSS
html5 Canvas画图教程(7)—canvas里画曲线之quadraticCurveTo方法
2013/01/09 HTML / CSS
HTML最新标准HTML5总结(必看)
2016/06/13 HTML / CSS
在weblogic中发布ejb需涉及到哪些配置文件
2012/01/17 面试题
学生爱国演讲稿
2014/01/14 职场文书
乡镇庆八一活动方案
2014/02/02 职场文书
服务之星事迹材料
2014/05/03 职场文书
优秀团员主要事迹范文
2015/11/05 职场文书
小学生安全教育心得体会
2016/01/15 职场文书