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 encode和decode的妙用
Sep 02 Python
举例讲解Django中数据模型访问外键值的方法
Jul 21 Python
python得到windows自启动列表的方法
Oct 14 Python
PyQt5实现简易计算器
May 30 Python
Pycharm简单使用教程(入门小结)
Jul 04 Python
python 直接赋值和copy的区别详解
Aug 07 Python
Python FTP文件定时自动下载实现过程解析
Nov 12 Python
python 画3维轨迹图并进行比较的实例
Dec 06 Python
在Django中自定义filter并在template中的使用详解
May 19 Python
python实现一次性封装多条sql语句(begin end)
Jun 06 Python
python gui开发——制作抖音无水印视频下载工具(附源码)
Feb 07 Python
Matplotlib绘制混淆矩阵的实现
May 27 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
动画 《Pokemon Sword·Shield》系列WEB动画《薄明之翼》第2话声优阵容公开!
2020/03/06 日漫
PHP.MVC的模板标签系统(一)
2006/09/05 PHP
新版PHP极大的增强功能和性能
2006/10/09 PHP
dedecms中常见问题修改方法总结
2007/03/21 PHP
php中关于socket的系列函数总结
2015/05/18 PHP
详细解读PHP的Yii框架中登陆功能的实现
2015/08/21 PHP
yii2利用自带UploadedFile实现上传图片的示例
2017/02/16 PHP
自己开发Dojo的建议框架
2008/09/24 Javascript
jQuery的实现原理的模拟代码 -1 核心部分
2010/08/01 Javascript
弹出层之1:JQuery.Boxy (一) 使用介绍
2011/10/06 Javascript
jQuery 如何先创建、再修改、后添加DOM元素
2014/05/20 Javascript
jquery 为a标签绑定click事件示例代码
2014/06/23 Javascript
使用DNode实现php和nodejs之间通信的简单实例
2015/07/06 NodeJs
JavaScript检查子字符串是否在字符串中的方法
2016/02/03 Javascript
jQuery控制文本框只能输入数字和字母及使用方法
2016/05/26 Javascript
javascript使用 concat 方法对数组进行合并的方法
2016/09/08 Javascript
jquery popupDialog 使用 加载jsp页面的方法
2016/10/25 Javascript
js利用for in循环获取 一个对象的所有属性以及值的实例
2017/03/30 Javascript
浅谈Node Inspector 代理实现
2017/10/19 Javascript
jQuery超简单遮罩层实现方法示例
2018/09/06 jQuery
修改layui的后台模板的左侧导航栏可以伸缩的方法
2019/09/10 Javascript
vant组件中 dialog的确认按钮的回调事件操作
2020/11/04 Javascript
Python 安装第三方库 pip install 安装慢安装不上的解决办法
2019/06/18 Python
详解python中的模块及包导入
2019/08/30 Python
Win10下python 2.7与python 3.7双环境安装教程图解
2019/10/12 Python
使用python把xmind转换成excel测试用例的实现代码
2020/10/12 Python
canvas学习笔记之2d画布基础的实现
2019/02/21 HTML / CSS
Lacoste(法国鳄鱼)加拿大官网:以标志性的POLO衫而闻名
2019/05/15 全球购物
香港百佳网上超级市场:PARKNSHOP.com
2020/06/10 全球购物
2014年国庆节演讲稿精选范文1500字
2014/09/25 职场文书
网络营销计划
2015/01/17 职场文书
学法用法心得体会(2016推荐篇)
2016/01/21 职场文书
SqlServer: 如何更改表的文件组?(进而改变存储位置)
2021/04/05 SQL Server
python基础之错误和异常处理
2021/10/24 Python
了解Kubernetes中的Service和Endpoint
2022/04/01 Servers
Oracle中DBLink的详细介绍
2022/04/29 Oracle