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实现统计单词出现的个数
May 28 Python
Python 用Redis简单实现分布式爬虫的方法
Nov 23 Python
python with提前退出遇到的坑与解决方案
Jan 05 Python
windows下python和pip安装教程
May 25 Python
Python实现的爬虫刷回复功能示例
Jun 07 Python
PyQt4编程之让状态栏显示信息的方法
Jun 18 Python
python读csv文件时指定行为表头或无表头的方法
Jun 26 Python
python实现复制大量文件功能
Aug 31 Python
python进程池实现的多进程文件夹copy器完整示例
Nov 27 Python
python接口自动化如何封装获取常量的类
Dec 24 Python
Python QT组件库qtwidgets的使用
Nov 02 Python
用基于python的appium爬取b站直播消费记录
Apr 17 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
linux下 C语言对 php 扩展
2008/12/14 PHP
PHP eval函数使用介绍
2013/12/08 PHP
JSON用法之将PHP数组转JS数组,JS如何接收PHP数组
2015/10/08 PHP
解决FireFox下[使用event很麻烦]的问题
2006/11/26 Javascript
在JavaScript中获取请求的URL参数[正则]
2010/12/25 Javascript
JS定时关闭窗口的实例
2013/05/22 Javascript
jQuery实现给页面换肤的方法
2015/05/30 Javascript
BootStrap 智能表单实战系列(二)BootStrap支持的类型简介
2016/06/13 Javascript
基于JavaScript代码实现自动生成表格
2016/06/15 Javascript
jQuery多级联动下拉插件chained用法示例
2016/08/20 Javascript
微信小程序 页面传参实例详解
2016/11/16 Javascript
关于微信上网页图片点击全屏放大效果
2016/12/19 Javascript
jQuery实现导航回弹效果
2017/02/27 Javascript
vue.js实现刷新当前页面的方法教程
2017/07/05 Javascript
JavaScript中错误正确处理方式小结你用对了吗
2017/10/10 Javascript
JavaScript实现数值自动增加动画
2017/12/28 Javascript
微信小程序实现上传图片功能
2018/05/28 Javascript
微信小程序实现canvas分享朋友圈海报
2020/06/21 Javascript
查找Vue中下标的操作(some和findindex)
2020/08/12 Javascript
Python 模拟购物车的实例讲解
2017/09/11 Python
python Celery定时任务的示例
2018/03/13 Python
Python操作Oracle数据库的简单方法和封装类实例
2018/05/07 Python
Python数据抓取爬虫代理防封IP方法
2018/12/23 Python
python sklearn常用分类算法模型的调用
2019/10/16 Python
自学python用什么系统好
2020/06/23 Python
Laura Mercier官网:彩妆大师罗拉玛斯亚的化妆品牌
2018/01/04 全球购物
英国儿童设计师服装的领先零售商:Base
2019/03/17 全球购物
Java多态性的定义以及类型
2014/09/16 面试题
.NET常见笔试题集
2012/12/01 面试题
学雷锋月活动总结
2014/04/25 职场文书
高中语文课后反思
2014/04/27 职场文书
新闻专业毕业生求职信
2014/08/08 职场文书
综合素质评价个性发展自我评价
2015/03/06 职场文书
劳保用品管理制度范本
2015/08/06 职场文书
2016年暑假家长对孩子评语
2015/12/01 职场文书
python四种出行路线规划的实现
2021/06/23 Python