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 相关文章推荐
Hadoop中的Python框架的使用指南
Apr 22 Python
Python实现对比不同字体中的同一字符的显示效果
Apr 23 Python
用Python编写简单的定时器的方法
May 02 Python
Python数据分析之双色球统计两个红和蓝球哪组合比例高的方法
Feb 03 Python
django admin 后台实现三级联动的示例代码
Jun 22 Python
在Python中使用defaultdict初始化字典以及应用方法
Oct 31 Python
Django中的forms组件实例详解
Nov 08 Python
python实现停车管理系统
Nov 30 Python
Python Pandas数据中对时间的操作
Jul 30 Python
Python中包的用法及安装
Feb 11 Python
Python发送邮件封装实现过程详解
May 09 Python
运行python提示no module named sklearn的解决方法
Nov 29 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实现短信发送代码
2015/07/05 PHP
PHP单例模式与工厂模式详解
2017/08/29 PHP
使用JS进行目录上传(相当于批量上传)
2010/12/05 Javascript
JavaScript 产生不重复的随机数三种实现思路
2012/12/13 Javascript
JavaScript之IE的fireEvent方法详细解析
2013/11/20 Javascript
JavaScript获取指定元素位置的方法
2015/04/08 Javascript
使用do...while的方法输入一个月中所有的周日(实例代码)
2016/07/22 Javascript
微信小程序中多个页面传参通信的学习与实践
2017/05/05 Javascript
js变量值传到php过程详解 将php解析成数据
2019/06/26 Javascript
微信小程序获取当前位置和城市名
2019/11/13 Javascript
微信小程序如何实现点击图片放大功能
2020/01/21 Javascript
Python3网络爬虫之使用User Agent和代理IP隐藏身份
2017/11/23 Python
对pandas读取中文unicode的csv和添加行标题的方法详解
2018/12/12 Python
Python如何优雅删除字符列表空字符及None元素
2020/06/25 Python
佳能加拿大网上商店:Canon eStore Canada
2018/04/04 全球购物
Nike香港官网:Nike HK
2019/03/23 全球购物
C#如何进行LDAP用户校验
2012/11/21 面试题
介绍一下Linux内核的排队自旋锁
2014/01/04 面试题
历史学专业个人的自我评价
2013/10/13 职场文书
人事部主管岗位职责
2013/12/26 职场文书
《乌塔》教学反思
2014/02/17 职场文书
客服部班长工作责任制
2014/02/25 职场文书
淘宝客服专员岗位职责
2014/04/11 职场文书
《灰椋鸟》教学反思
2014/04/27 职场文书
基层党支部公开承诺书
2014/05/29 职场文书
小学老师对学生的评语
2014/12/29 职场文书
2015年房产销售工作总结范文
2015/05/22 职场文书
毕业论文答辩开场白
2015/05/27 职场文书
2015年大学生暑期实习报告
2015/07/13 职场文书
如何写好开幕词?
2019/06/24 职场文书
《童年》读后感(三篇)
2019/08/27 职场文书
python spilt()分隔字符串的实现示例
2021/05/21 Python
浅谈MySql整型索引和字符串索引失效或隐式转换问题
2021/11/20 MySQL
MySQL 自动填充 create_time 和 update_time
2022/05/20 MySQL
Redis基本数据类型String常用操作命令
2022/06/01 Redis