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文本特征抽取与向量化算法学习
Dec 22 Python
使用pandas中的DataFrame数据绘制柱状图的方法
Apr 10 Python
基于DATAFRAME中元素的读取与修改方法
Jun 08 Python
Python 单元测试(unittest)的使用小结
Nov 14 Python
零基础使用Python读写处理Excel表格的方法
May 02 Python
详解Python sys.argv使用方法
May 10 Python
Python编程实现tail-n查看日志文件的方法
Jul 08 Python
python字典的setdefault的巧妙用法
Aug 07 Python
python爬虫库scrapy简单使用实例详解
Feb 10 Python
Python threading模块condition原理及运行流程详解
Oct 05 Python
python绘制高斯曲线
Feb 19 Python
浅析python中特殊文件和特殊函数
Feb 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
ThinkPHP模版中导入CSS和JS文件的方法
2014/11/29 PHP
PHP简单的MVC框架实现方法
2015/12/01 PHP
简单谈谈php延迟静态绑定
2016/01/26 PHP
简单谈谈PHP中的trait
2017/02/25 PHP
visual studio code 调试php方法(图文详解)
2017/09/15 PHP
js/jQuery对象互转(快速操作dom元素)
2013/02/04 Javascript
百度地图自定义控件分享
2015/03/04 Javascript
javascript适合移动端的日期时间拾取器
2015/11/10 Javascript
基于Vuejs实现购物车功能
2016/08/02 Javascript
正则中的回溯定义与用法分析【JS与java实现】
2016/12/27 Javascript
Node.js中用D3.js的方法示例
2017/01/16 Javascript
Vue表单验证插件Vue Validator使用方法详解
2017/04/07 Javascript
mui框架 页面无法滚动的解决方法(推荐)
2018/01/25 Javascript
微信小程序form表单组件示例代码
2018/07/15 Javascript
Vue 处理表单input单行文本框的实例代码
2019/05/09 Javascript
通过实践编写优雅的JavaScript代码
2019/05/30 Javascript
微信小程序开发(三):返回上一级页面并刷新操作示例【页面栈】
2020/06/01 Javascript
[50:59]2018DOTA2亚洲邀请赛 4.7 总决赛 LGD vs Mineski第四场
2018/04/10 DOTA
Python实现常见的回文字符串算法
2018/11/14 Python
Python中的十大图像处理工具(小结)
2019/06/10 Python
结合OpenCV与TensorFlow进行人脸识别的实现
2019/10/10 Python
python爬虫爬取笔趣网小说网站过程图解
2019/11/18 Python
python使用opencv在Windows下调用摄像头实现解析
2019/11/26 Python
pyinstaller将含有多个py文件的python程序做成exe
2020/04/29 Python
python pyg2plot的原理知识点总结
2021/02/28 Python
萨克斯第五大道的折扣店:Saks Fifth Avenue OFF 5TH
2016/08/25 全球购物
linux面试题参考答案(8)
2015/08/11 面试题
30岁生日感言
2014/01/25 职场文书
运动会获奖感言
2014/02/11 职场文书
事假请假条范文
2014/04/11 职场文书
个人委托书怎么写
2014/09/17 职场文书
学校党的群众路线教育实践活动领导班子对照检查材料
2014/09/25 职场文书
2014年技术工作总结范文
2014/11/20 职场文书
大三学生英语考试作弊检讨书
2015/01/01 职场文书
MySQL Shell的介绍以及安装
2021/04/24 MySQL
vscode中使用npm安装babel的方法
2021/08/02 Javascript