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实现异步回调机制代码分享
Jan 10 Python
详细讲解用Python发送SMTP邮件的教程
Apr 29 Python
Python多线程和队列操作实例
Jun 21 Python
Python的语言类型(详解)
Jun 24 Python
python字符串与url编码的转换实例
May 10 Python
Python3.6.0+opencv3.3.0人脸检测示例
May 25 Python
python实现朴素贝叶斯算法
Nov 19 Python
python圣诞树编写实例详解
Feb 13 Python
Python迭代器Iterable判断方法解析
Mar 16 Python
Python面向对象程序设计之类和对象、实例变量、类变量用法分析
Mar 23 Python
Python 实现国产SM3加密算法的示例代码
Sep 21 Python
python读取excel数据并且画图的实现示例
Feb 08 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
咖啡产品发展的三大浪潮
2021/03/04 咖啡文化
php发送html格式文本邮件的方法
2015/06/10 PHP
优化WordPress的Google字体以加速国内服务器上的运行
2015/11/24 PHP
php分享朋友圈的实现代码
2019/02/18 PHP
Js 订制自己的AlertBox(信息提示框)
2009/01/09 Javascript
JavaScript 匿名函数(anonymous function)与闭包(closure)
2011/10/04 Javascript
jQuery学习笔记 操作jQuery对象 CSS处理
2012/09/19 Javascript
将Datatable转化成json发送前台实现思路
2013/09/06 Javascript
nodejs获取本机内网和外网ip地址的实现代码
2014/06/01 NodeJs
AngularJS初始化过程分析(引导程序)
2014/12/06 Javascript
javascript实现类似超链接的效果
2014/12/26 Javascript
JQuery select(下拉框)操作方法汇总
2015/04/15 Javascript
jquery实现简单文字提示效果
2015/12/02 Javascript
基于jquery实现图片上传本地预览功能
2016/01/08 Javascript
JavaScript html5 canvas绘制时钟效果(二)
2016/03/27 Javascript
详解nodejs与javascript中的aes加密
2016/05/22 NodeJs
基于Vue实现支持按周切换的日历
2020/09/24 Javascript
MUI顶部选项卡的用法(tab-top-webview-main)详解
2017/10/08 Javascript
jQuery访问浏览器本地存储cookie、localStorage和sessionStorage的基本用法
2017/10/20 jQuery
微信小程序与公众号实现数据互通的方法
2019/07/25 Javascript
JS实现滑动拼图验证功能完整示例
2020/03/29 Javascript
python使用scrapy解析js示例
2014/01/23 Python
Windows下使Python2.x版本的解释器与3.x共存的方法
2015/10/25 Python
Python程序退出方式小结
2017/12/09 Python
Python使用matplotlib绘制三维图形示例
2018/08/25 Python
Python实现井字棋小游戏
2020/03/09 Python
html5定位并在百度地图上显示的示例
2014/04/27 HTML / CSS
静态变量和实例变量的区别
2015/07/07 面试题
涉外文秘个人求职的自我评价
2013/10/07 职场文书
文史专业毕业生自荐信
2013/11/17 职场文书
2014年社区庆元旦活动方案
2014/03/08 职场文书
感恩父母的演讲稿
2014/05/06 职场文书
心得体会的写法
2014/09/05 职场文书
个人融资协议书范本两则
2014/10/15 职场文书
2016年国庆节宣传标语
2015/11/25 职场文书
sql中mod()函数取余数的用法
2021/05/29 SQL Server