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中http请求方法库汇总
Jan 06 Python
使用python调用zxing库生成二维码图片详解
Jan 10 Python
python提取包含关键字的整行数据方法
Dec 11 Python
Python基本数据结构与用法详解【列表、元组、集合、字典】
Mar 23 Python
用python拟合等角螺线的实现示例
Dec 27 Python
TensorFlow获取加载模型中的全部张量名称代码
Feb 11 Python
python使用pyecharts库画地图数据可视化的实现
Mar 25 Python
解决python 执行sql语句时所传参数含有单引号的问题
Jun 06 Python
python安装及变量名介绍详解
Dec 12 Python
pycharm 实现调试窗口恢复
Feb 05 Python
详解NumPy中的线性关系与数据修剪压缩
May 25 Python
python可视化分析绘制带趋势线的散点图和边缘直方图
Jun 25 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函数
2010/01/11 PHP
php将字符串转化成date存入数据库的两种方式
2014/04/28 PHP
Laravel框架中扩展函数、扩展自定义类的方法
2014/09/04 PHP
Laravel框架Eloquent ORM修改数据操作示例
2019/12/03 PHP
JavaScript的面向对象方法以及差别
2008/03/31 Javascript
js滚动条回到顶部的代码
2011/12/06 Javascript
jQuery的3种请求方式$.post,$.get,$.getJSON
2014/03/28 Javascript
vue插件tab选项卡使用小结
2016/10/27 Javascript
BootStrap表单验证实例代码
2017/01/13 Javascript
微信小程序中子页面向父页面传值实例详解
2017/03/20 Javascript
浅谈用Webpack路径压缩图片上传尺寸获取的问题
2018/02/22 Javascript
利用jquery和BootStrap实现动态滚动条效果
2018/12/03 jQuery
layui监听下拉选框选中值变化的方法(包含监听普通下拉选框)
2019/09/24 Javascript
JS对象属性的检测与获取操作实例分析
2020/03/17 Javascript
Vue项目vscode 安装eslint插件的方法(代码自动修复)
2020/04/15 Javascript
javascript的hashCode函数实现代码小结
2020/08/11 Javascript
如何使用jQuery操作Cookies方法解析
2020/09/08 jQuery
如何使用gpu.js改善JavaScript的性能
2020/12/01 Javascript
python备份文件的脚本
2008/08/11 Python
手动实现把python项目发布为exe可执行程序过程分享
2014/10/23 Python
Python 使用with上下文实现计时功能
2018/03/09 Python
解决Django数据库makemigrations有变化但是migrate时未变动问题
2018/05/30 Python
flask框架单元测试原理与用法实例分析
2019/07/23 Python
Django配置文件代码说明
2019/12/04 Python
使用python创建生成动态链接库dll的方法
2020/05/09 Python
Django用内置方法实现简单搜索功能的方法
2020/12/18 Python
美国购买和销售礼品卡平台:Raise
2017/01/13 全球购物
Anya Hindmarch官网:奢侈设计师手袋及配饰
2018/11/15 全球购物
运动会通讯稿100字
2014/01/31 职场文书
班主任工作经验材料
2014/02/02 职场文书
诚信贷款承诺书
2014/05/30 职场文书
戒毒悔改检讨书
2014/09/21 职场文书
党员民主评议总结
2014/10/20 职场文书
校长个人总结
2015/03/03 职场文书
优秀毕业生主要事迹材料
2015/11/04 职场文书
用Python将库打包发布到pypi
2021/04/13 Python