重学。

# coding = utf-8

# 二叉树遍历
class Node:
    """节点类"""
    def __init__(self, element=None, left_child=None, right_child=None):
        self.element = element
        self.left_child = left_child
        self.right_child = right_child

class Tree:
    """树类"""
    def __init__(self):
        self.root = Node()
        self.tree_queue = []

    def add(self, element):
        """为树添加节点"""
        node = Node(element)
        if self.root.element is None:
            self.root = node
            self.tree_queue.append(self.root)
        else:
            tree_node = self.tree_queue[0]
            if tree_node.left_child is None:
                tree_node.left_child = node
                self.tree_queue.append(tree_node.left_child)
            else:
                tree_node.right_child = node
                self.tree_queue.append(tree_node.right_child)
                self.tree_queue.pop(0)

    def front_recursion(self, root):
        """利用递归实现树的先序遍历"""
        if root is None:
            return
        print(root.element, end=' ')
        self.front_recursion(root.left_child)
        self.front_recursion(root.right_child)

    def middle_recursion(self, root):
        """利用递归实现树的中序遍历"""
        if root is None:
            return
        self.middle_recursion(root.left_child)
        print(root.element, end=' ')
        self.middle_recursion(root.right_child)

    def later_recursion(self, root):
        """利用递归实现树的后序遍历"""
        if root is None:
            return
        self.later_recursion(root.left_child)
        self.later_recursion(root.right_child)
        print(root.element, end=' ')

    def front_stack(self, root):
        """利用堆栈实现树的先序遍历"""
        if root is None:
            return
        tree_stack = []
        node = root
        while node or tree_stack:
            while node:
                print(node.element, end=' ')
                tree_stack.append(node)
                node = node.left_child
            node = tree_stack.pop()
            node = node.right_child

    def middle_stack(self, root):
        """利用堆栈实现树的中序遍历"""
        if root is None:
            return
        tree_stack = []
        node = root
        while node or tree_stack:
            while node:
                tree_stack.append(node)
                node = node.left_child
            node = tree_stack.pop()
            print(node.element, end=' ')
            node = node.right_child

    def later_stack(self, root):
        """利用堆栈实现树的后序遍历"""
        if root is None:
            return
        tree_stack_a = []
        tree_stack_b = []
        node = root
        tree_stack_a.append(node)
        while tree_stack_a:
            node = tree_stack_a.pop()
            if node.left_child:
                tree_stack_a.append(node.left_child)
            if node.right_child:
                tree_stack_a.append(node.right_child)
            tree_stack_b.append(node)
        while tree_stack_b:
            print(tree_stack_b.pop().element, end=' ')

    def level_queue(self, root):
        """利用队列实现树的层次遍历"""
        if root is None:
            return
        tree_queue = []
        node = root
        tree_queue.append(node)
        while tree_queue:
            node = tree_queue.pop(0)
            print(node.element, end=' ')
            if node.left_child is not None:
                tree_queue.append(node.left_child)
            if node.right_child is not None:
                tree_queue.append(node.right_child)

if __name__ == '__main__':
    elem_s = range(10)
    # 新建一个二叉树对象
    tree = Tree()
    for elem in elem_s:
        tree.add(elem)

    print('广度优先遍历---队列实现层次遍历:')
    tree.level_queue(tree.root)
    print('\n深度优先遍历---递归实现先序遍历:')
    tree.front_recursion(tree.root)
    print('\n深度优先遍历---递归实现中序遍历:')
    tree.middle_recursion(tree.root)
    print('\n深度优先遍历---递归实现后序遍历:')
    tree.later_recursion(tree.root)
    print('\n深度优先遍历---堆栈实现先序遍历:')
    tree.front_stack(tree.root)
    print('\n深度优先遍历---堆栈实现中序遍历:')
    tree.middle_stack(tree.root)
    print('\n深度优先遍历---堆栈实现后序遍历:')
    tree.later_stack(tree.root)
C:\Users\Sahara\.virtualenvs\test\Scripts\python.exe C:/Users/Sahara/PycharmProjects/test/python_search.py
广度优先遍历---队列实现层次遍历:

深度优先遍历---递归实现先序遍历:

深度优先遍历---递归实现中序遍历:

深度优先遍历---递归实现后序遍历:

深度优先遍历---堆栈实现先序遍历:

深度优先遍历---堆栈实现中序遍历:

深度优先遍历---堆栈实现后序遍历:

Process finished with exit code 

python---二叉树遍历的更多相关文章

  1. Python --- 二叉树的层序建立与三种遍历

    二叉树(Binary Tree)时数据结构中一个非常重要的结构,其具有....(此处省略好多字)....等的优良特点. 之前在刷LeetCode的时候把有关树的题目全部跳过了,(ORZ:我这种连数据结 ...

  2. python实现二叉树遍历算法

    说起二叉树的遍历,大学里讲的是递归算法,大多数人首先想到也是递归算法.但作为一个有理想有追求的程序员.也应该学学非递归算法实现二叉树遍历.二叉树的非递归算法需要用到辅助栈,算法着实巧妙,令人脑洞大开. ...

  3. Python -二叉树 创建与遍历算法(很详细)

    树表示由边连接的节点.它是一个非线性的数据结构.它具有以下特性. 一个节点被标记为根节点. 除根节点之外的每个节点都与一个父节点关联. 每个节点可以有一个arbiatry编号的chid节点. 我们使用 ...

  4. 二叉树遍历(非递归版)——python

    二叉树的遍历分为广度优先遍历和深度优先遍历 广度优先遍历(breadth first traversal):又称层次遍历,从树的根节点(root)开始,从上到下从从左到右遍历整个树的节点. 深度优先遍 ...

  5. 算法随笔-二叉树遍历的N种姿势

    最近在练习用Python刷算法,leetcode上刷了快300题.一开始怀疑自己根本不会写代码,现在觉得会写一点点了,痛苦又充实的刷题历程.对我这种半路出家的人而言,收获真的很大. 今天就从二叉树遍历 ...

  6. Python - 二叉树, 堆, headq 模块

    二叉树 概念 二叉树是n(n>=0)个结点的有限集合,该集合或者为空集(称为空二叉树), 或者由一个根结点和两棵互不相交的.分别称为根结点的左子树和右子树组成. 特点 每个结点最多有两颗子树,所 ...

  7. python 实时遍历日志文件

    首先尝试使用 python open 遍历一个大日志文件, 使用 readlines() 还是 readline() ? 总体上 readlines() 不慢于python 一次次调用 readlin ...

  8. C++ 二叉树遍历实现

    原文:http://blog.csdn.net/nuaazdh/article/details/7032226 //二叉树遍历 //作者:nuaazdh //时间:2011年12月1日 #includ ...

  9. 【二叉树遍历模版】前序遍历&&中序遍历&&后序遍历&&层次遍历&&Root->Right->Left遍历

    [二叉树遍历模版]前序遍历     1.递归实现 test.cpp: 12345678910111213141516171819202122232425262728293031323334353637 ...

  10. hdu 4605 线段树与二叉树遍历

    思路: 首先将所有的查询有一个vector保存起来.我们从1号点开始dfs这颗二叉树,用线段树记录到当前节点时,走左节点的有多少比要查询该节点的X值小的,有多少大的, 同样要记录走右节点的有多少比X小 ...

随机推荐

  1. mpvue——页面跳转

    两个页面 两个页面的跳转,只是单纯的A->B这种跳转. 组件 直接使用小程序的组件,navigator,里面还有一些其他的参数,大家可以自行翻阅官方文档 <navigator url=&q ...

  2. CSS3基础入门01

    CSS3 基础入门 01 前言 相对于css2来说,css3更新了很多的内容,其中包括选择器.颜色.阴影.背景.文本.边框.新的布局方案.2d.3d.动画等等. 而如果想要学习css3的诸多部分,不妨 ...

  3. css经常使用的六种文本样式

    css当中经常使用的六种文本样式 css 文本样式是相对于内容进行的样式修饰,下面来说下几种常见的文本样式. 首行缩进 首行缩进是将段落的第一行缩进,这是常用的文本格式化效果.一般地,中文写作时开头空 ...

  4. [问题]Android listView item edittext 不能调用软键盘输入法

    android listview item edittext not  softkeyboard edittext可以获取焦点, 可以触发事件, 但是就是不能调用输入法, 不知道为什么? 难道不能在i ...

  5. docker_weave

    安装 curl -L git.io/weave -o /usr/local/bin/weave chmod a+x /usr/local/bin/weave 启动 weave weave launch ...

  6. CentOS配置history记录每个用户执行过的命令

    一个偶然的机会,看到了这个文档,先存下来,后续使用的话直接就加进去了 要记录登录者的用户名.IP.操作记录,在/etc/bashrc末尾加入几个环境变量,用于history命令显示用户ip等内容,完成 ...

  7. python利用selenium库识别点触验证码

    利用selenium库和超级鹰识别点触验证码(学习于静谧大大的书,想自己整理一下思路) 一.超级鹰注册:超级鹰入口 1.首先注册一个超级鹰账号,然后在超级鹰免费测试地方可以关注公众号,领取1000积分 ...

  8. GCC __builtin_expect的作用

    https://blog.csdn.net/shuimuniao/article/details/8017971 #define LIKELY(x) __builtin_expect(!!(x), 1 ...

  9. tqdm的使用方法

    Tqdm 是一个快速,可扩展的Python进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器 tqdm(iterator),使用pip就可以安装 使用方法主要是:t ...

  10. 第三节:总结.Net下后端的几种请求方式(WebClient、WebRequest、HttpClient)

    一. 前言 前端调用有Form表单提交,ajax提交,ajax一般是用Jquery的简化写法,在这里不再过多介绍: 后端调用大约有这些:WebCient.WebRequest.Httpclient.W ...