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直接访问私有属性的简单方法
Jul 25 Python
Python实现简单的多任务mysql转xml的方法
Feb 08 Python
Python字符串拼接的几种方法整理
Aug 02 Python
PyQt5主窗口动态加载Widget实例代码
Feb 07 Python
利用python GDAL库读写geotiff格式的遥感影像方法
Nov 29 Python
python虚拟环境迁移方法
Jan 03 Python
Python中new方法的详解
Jan 15 Python
python3实现微型的web服务器
Sep 03 Python
pandas按行按列遍历Dataframe的几种方式
Oct 23 Python
django admin后管定制-显示字段的实例
Mar 11 Python
Python调用C/C++的方法解析
Aug 05 Python
pycharm无法安装cv2模块问题
May 20 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
php无限遍历目录示例
2014/02/21 PHP
JS求平均值的小例子
2013/11/29 Javascript
关于js内存泄露的一个好例子
2013/12/09 Javascript
使用jquery animate创建平滑滚动效果(可以是到顶部、到底部或指定地方)
2014/05/27 Javascript
深入理解JavaScript系列(18):面向对象编程之ECMAScript实现
2015/03/05 Javascript
jQuery的基本概念与高级编程
2015/05/14 Javascript
javascript实现类似于新浪微博搜索框弹出效果的方法
2015/07/27 Javascript
Bootstrap滚动监听组件scrollspy.js使用方法详解
2017/07/20 Javascript
详解Vue2 SSR 缓存 Api 数据
2017/11/20 Javascript
JavaScript递归函数解“汉诺塔”算法代码解析
2018/07/05 Javascript
js实现移动端轮播图
2020/12/21 Javascript
json 带斜杠时如何解析的实现
2019/08/12 Javascript
解决VUE双向绑定失效的问题
2019/10/29 Javascript
vue请求服务器数据后绑定不上的解决方法
2019/10/30 Javascript
node运行js获得输出的三种方式示例详解
2020/07/02 Javascript
Python RuntimeError: thread.__init__() not called解决方法
2015/04/28 Python
wxPython的安装与使用教程
2018/08/31 Python
pandas通过loc生成新的列方法
2018/11/28 Python
Python 3.6 -win64环境安装PIL模块的教程
2019/06/20 Python
利用python开发app实战的方法
2019/07/09 Python
Python获取时间范围内日期列表和周列表的函数
2019/08/05 Python
Python实现变声器功能(萝莉音御姐音)
2019/12/05 Python
Python文件操作方法详解
2020/02/09 Python
Python loguru日志库之高效输出控制台日志和日志记录
2020/03/07 Python
CSS3 mask 遮罩的具体使用方法
2017/11/03 HTML / CSS
HTML5 Canvas 破碎重组的视频特效的示例代码
2019/09/24 HTML / CSS
HTML5 localStorage使用总结
2017/02/22 HTML / CSS
介绍一下内联、左联、右联
2013/12/31 面试题
2014年小学植树节活动方案
2014/03/02 职场文书
美容院营销方案
2014/03/05 职场文书
说明书范文
2014/05/07 职场文书
乔丹名人堂演讲稿
2014/05/24 职场文书
预防传染病方案
2014/06/14 职场文书
党的群众路线教育实践活动个人整改落实情况汇报
2014/10/28 职场文书
golang 实现两个结构体复制字段
2021/04/28 Golang
mybatis-plus模糊查询指定字段
2022/04/28 Java/Android