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程序设计入门(1)基本语法简介
Jun 13 Python
python中使用enumerate函数遍历元素实例
Jun 16 Python
Python跳出循环语句continue与break的区别
Aug 25 Python
Python中利用sorted()函数排序的简单教程
Apr 27 Python
python中requests使用代理proxies方法介绍
Oct 25 Python
对PyQt5基本窗口控件 QMainWindow的使用详解
Jun 19 Python
在Pandas中处理NaN值的方法
Jun 25 Python
Python工程师必考的6个经典面试题
Jun 28 Python
Python DataFrame使用drop_duplicates()函数去重(保留重复值,取重复值)
Jul 20 Python
PyTorch中Tensor的数据类型和运算的使用
Sep 03 Python
python实现发送邮件
Mar 02 Python
Python echarts实现数据可视化实例详解
Mar 03 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 字符串替换的方法
2012/01/10 PHP
WordPress中查询文章的循环Loop结构及用法分析
2015/12/17 PHP
PHP排序算法之冒泡排序(Bubble Sort)实现方法详解
2018/04/20 PHP
微信公众平台开发教程④ ThinkPHP框架下微信支付功能图文详解
2019/04/10 PHP
让iframe子窗体取父窗体地址栏参数(querystring)
2009/10/13 Javascript
js 获取计算后的样式写法及注意事项
2013/02/25 Javascript
js格式化货币数据实现代码
2013/09/04 Javascript
jquery中交替点击事件toggle方法的使用示例
2013/12/08 Javascript
JS中的构造函数详细解析
2014/03/10 Javascript
javascript下拉框选项单击事件的例子分享
2015/03/04 Javascript
jquery序列化方法实例分析
2015/06/10 Javascript
详解JavaScript ES6中的Generator
2015/07/28 Javascript
深入理解jQuery事件绑定
2016/06/02 Javascript
jQuery  ready方法实现原理详解
2016/10/19 Javascript
jQuery实现遮罩层登录对话框
2016/12/29 Javascript
微信小程序实现点击按钮修改文字大小功能【附demo源码下载】
2017/12/06 Javascript
详解如何实现Element树形控件Tree在懒加载模式下的动态更新
2019/04/25 Javascript
JS中数据结构与算法---排序算法(Sort Algorithm)实例详解
2019/06/17 Javascript
一篇超完整的Vue新手入门指导教程
2020/11/18 Vue.js
[02:12]打造更好的电竞完美世界:完美盛典回顾篇
2018/12/19 DOTA
Python模块包中__init__.py文件功能分析
2016/06/14 Python
python字符串与url编码的转换实例
2018/05/10 Python
详解python的sorted函数对字典按key排序和按value排序
2018/08/10 Python
Django 1.10以上版本 url 配置注意事项详解
2019/08/05 Python
Python发起请求提示UnicodeEncodeError错误代码解决方法
2020/04/21 Python
html5 viewport使用方法示例详解
2013/12/02 HTML / CSS
SISLEY希思黎官方旗舰店:享誉全球的奢华植物美容品牌
2018/04/25 全球购物
美国演唱会和体育门票购买网站:Ticketnetwork
2018/10/19 全球购物
大学生军训自我评价分享
2013/11/09 职场文书
工作决心书
2014/03/11 职场文书
心得体会的写法
2014/09/05 职场文书
干部竞争上岗演讲稿
2014/09/11 职场文书
民政局未婚证明
2015/06/15 职场文书
2015年新农村建设指导员工作总结
2015/07/24 职场文书
MongoDB orm框架的注意事项及简单使用
2021/06/20 MongoDB
SQL语法CONSTRAINT约束操作详情
2022/01/18 MySQL