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 27 Python
Python入门_浅谈逻辑判断与运算符
May 16 Python
Python2随机数列生成器简单实例
Sep 04 Python
python unittest实现api自动化测试
Apr 04 Python
pandas 透视表中文字段排序方法
Nov 16 Python
大家都说好用的Python命令行库click的使用
Nov 07 Python
Django 请求Request的具体使用方法
Nov 11 Python
Python Sympy计算梯度、散度和旋度的实例
Dec 06 Python
python Popen 获取输出,等待运行完成示例
Dec 30 Python
python判断链表是否有环的实例代码
Jan 31 Python
python数据预处理 :数据共线性处理详解
Feb 24 Python
python实现用户名密码校验
Mar 18 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实现有趣的人品测试程序实例
2015/06/08 PHP
php array_reverse 以相反的顺序返回数组实例代码
2017/04/11 PHP
sina的lightbox效果。
2007/01/09 Javascript
jQuery实现列表自动滚动循环滚动展示新闻
2014/08/22 Javascript
jQuery晃动层特效实现方法
2015/03/09 Javascript
jQuery实现带滚动导航效果的全屏滚动相册实例
2015/06/19 Javascript
每天一篇javascript学习小结(Date对象)
2015/11/13 Javascript
基于jQuery日历插件制作日历
2016/03/11 Javascript
Bootstrap按钮下拉菜单组件详解
2016/05/10 Javascript
省市二级联动小案例讲解
2016/07/24 Javascript
Extjs gridpanel 中的checkbox(复选框)根据某行的条件不能选中的解决方法
2017/02/17 Javascript
Vue.js展示AJAX数据简单示例讲解
2017/03/29 Javascript
Vue中img的src属性绑定与static文件夹实例
2017/05/18 Javascript
Angular4如何自定义首屏的加载动画详解
2017/07/26 Javascript
es6中的解构赋值、扩展运算符和rest参数使用详解
2017/09/28 Javascript
JSON 入门教程基础篇 json入门学习笔记
2020/09/22 Javascript
JPype实现在python中调用JAVA的实例
2017/07/19 Python
Python迭代器与生成器基本用法分析
2018/07/26 Python
python通过tcp发送xml报文的方法
2018/12/28 Python
Python使用pymysql模块操作mysql增删改查实例分析
2019/12/19 Python
Python greenlet和gevent使用代码示例解析
2020/04/01 Python
python单元测试框架pytest的使用示例
2020/10/07 Python
纯CSS3实现圆圈动态发光特效动画的示例代码
2021/03/08 HTML / CSS
HTML5实现页面切换激活的PageVisibility API使用初探
2016/05/13 HTML / CSS
英国太阳镜品牌:Taylor Morris Eyewear
2018/04/18 全球购物
Linux管理员面试题 Linux admin interview questions
2016/07/08 面试题
学生处主任岗位职责
2013/12/01 职场文书
促销活动总结范文
2014/04/30 职场文书
军人离婚协议书样本
2014/10/21 职场文书
保研推荐信格式
2015/03/25 职场文书
针对吵架老公保证书
2015/05/08 职场文书
2016年3月份红领巾广播稿
2015/12/21 职场文书
2016年社区六一儿童节活动总结
2016/04/06 职场文书
如何用JavaScript实现一个数组惰性求值库
2021/05/05 Javascript
MySql统计函数COUNT的具体使用详解
2022/08/14 MySQL