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 列表(List)操作方法详解
Mar 11 Python
用python + openpyxl处理excel2007文档思路以及心得
Jul 14 Python
python实现马耳可夫链算法实例分析
May 20 Python
python利用装饰器进行运算的实例分析
Aug 04 Python
Python编程实现正则删除命令功能
Aug 30 Python
Python实现螺旋矩阵的填充算法示例
Dec 28 Python
pandas 数据索引与选取的实现方法
Jun 21 Python
python scipy卷积运算的实现方法
Sep 16 Python
Python requests上传文件实现步骤
Sep 15 Python
安装pyinstaller遇到的各种问题(小结)
Nov 20 Python
python 基于opencv操作摄像头
Dec 24 Python
Python中使用Opencv开发停车位计数器功能
Apr 04 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作的文本留言本的例子(二)
2006/10/09 PHP
php比较多维数组中值的大小排序实现代码
2012/09/08 PHP
探讨PHP使用eAccelerator的API开发详解
2013/06/09 PHP
Linux安装配置php环境的方法
2016/01/14 PHP
浅谈JavaScript编程语言的编码规范
2011/10/21 Javascript
jQuery操作 input type=checkbox的实现代码
2012/06/14 Javascript
nodejs中使用monk访问mongodb
2014/07/06 NodeJs
Javascript基于AJAX回调函数传递参数实例分析
2015/12/15 Javascript
分享有关jQuery中animate、slide、fade等动画的连续触发、滞后反复执行的bug
2016/01/10 Javascript
js实现鼠标左右移动,图片也跟着移动效果
2017/01/25 Javascript
js简单实现网页换肤功能
2017/04/07 Javascript
JS+Canvas绘制动态时钟效果
2017/11/10 Javascript
Node.js Buffer用法解读
2018/05/18 Javascript
Vue 路由切换时页面内容没有重新加载的解决方法
2018/09/01 Javascript
解决layui批量传值到后台操作时出现传值为空的问题
2019/09/28 Javascript
Node.js中文件系统fs模块的使用及常用接口
2020/03/06 Javascript
微信小程序搜索框样式并实现跳转到搜索页面(小程序搜索功能)
2020/03/10 Javascript
prettier自动格式化去换行的实现代码
2020/08/25 Javascript
python中的装饰器详解
2015/04/13 Python
在Python web中实现验证码图片代码分享
2017/11/09 Python
python批量读取txt文件为DataFrame的方法
2018/04/03 Python
Python动态生成多维数组的方法示例
2018/08/09 Python
在Python中如何传递任意数量的实参的示例代码
2019/03/21 Python
python频繁写入文件时提速的方法
2019/06/26 Python
python保存字典和读取字典的实例代码
2019/07/07 Python
python爬虫把url链接编码成gbk2312格式过程解析
2020/06/08 Python
利于python脚本编写可视化nmap和masscan的方法
2020/12/29 Python
英语专业毕业生求职简历的自我评价
2013/10/24 职场文书
初二生物教学反思
2014/02/03 职场文书
书法比赛获奖感言
2014/02/10 职场文书
卫生系统先进事迹
2014/05/13 职场文书
金融专业毕业生自荐信
2014/06/26 职场文书
2014小学生国庆65周年演讲稿
2014/09/21 职场文书
2015年医院后勤工作总结
2015/05/20 职场文书
mongodb的安装和开机自启动详细讲解
2021/08/02 MongoDB
详解Vue3使用axios的配置教程
2022/04/29 Vue.js