美文网首页
python数据结构-树

python数据结构-树

作者: 薛皓哲 | 来源:发表于2017-08-09 09:04 被阅读114次

树是数据结构中常用到的一种结构,其实现较栈和队稍为复杂一些。若树中的所有节点的孩子节点数量不超过2个,则该为一个二叉树。


“嵌套列表”表示树

2017080815021788582607.png 20170808150217857149175.png
myTree = ['a',   #root
      ['b',  #left subtree
       ['d' [], []],
       ['e' [], []] ],
      ['c',  #right subtree
       ['f' [], []],
       [] ]
     ]

myTree = ['a', ['b', ['d',[],[]], ['e',[],[]] ], ['c', ['f',[],[]], []] ]
print(myTree)
print('left subtree = ', myTree[1])
print('root = ', myTree[0])
print('right subtree = ', myTree[2])

树的根是myTree[0],根的左子树是myTree[1],和右子树是myTree[2]

二叉树

20170808150217865294242.png 20170808150217881617379.png 20170808150217917424511.png
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by xuehz on 2017/8/8

#二叉树

class Tree():
    def __init__(self, leftjd=0, rightjd=0, data =0):
        self.leftjd = leftjd
        self.rightjd = rightjd
        self.data = data

class Btree():
    def __init__(self, base = 0):
        self.base = base
    def empty(self):
        if self.base is 0:
            return True
        else:
            return False
    def qout(self, jd):
        """
        前序遍历 NLR 根左右
        :param jd:
        :return:
        """
        if jd == 0:
            return
        print jd.data
        self.qout(jd.leftjd) #递归调用
        self.qout(jd.rightjd)
    def mout(self,jd):
        """
        中序遍历 LNR 左根右
        :param jd:
        :return:
        """
        if jd == 0:
            return
        self.qout(jd.leftjd)
        print jd.data
        self.qout(jd.rightjd)

    def hout(self,jd):
        """
        后序遍历 LRN 左右根
        :param jd:
        :return:
        """
        if jd ==0:
            return
        self.qout(jd.leftjd)  # 递归调用
        self.qout(jd.rightjd)
        print jd.data

if __name__ == '__main__':
    dj1 = Tree(data=8)
    dj2 = Tree(data=9)
    base = Tree(dj1, dj2, 7)# 根节点
    x = Btree(base)
    x.qout(x.base)
    print '========'
    x.mout(x.base)
    print '========'
    x.hout(x.base)


相关文章

  • 个人 Python 书单

    入门: Beginning Python 数据结构: Python 数据结构 算法: Python 算法教程

  • Python-list 和 dict 内置操作的时间复杂度

    Python的 list 数据结构 Python dict 数据结构

  • 6-Python 数据结构初识

    课程概要:1、Python 数据结构概述2、Python 常见数据结构——栈3、Python 常见数据结构——队列...

  • python数据结构-树

    树是数据结构中常用到的一种结构,其实现较栈和队稍为复杂一些。若树中的所有节点的孩子节点数量不超过2个,则该为一个二...

  • 数据结构-树以及深度、广度优先遍历

    数据结构-树以及深度、广度优先遍历(递归和非递归,python实现)[https://www.cnblogs.co...

  • 数据结构 - 概要

    数组 链表 堆/栈/队列 树 数据结构 - 二叉树数据结构 - 二叉查找树数据结构 - 平衡二叉树数据结构 - A...

  • 《python算法教程》Day2 - 图和树的基本数据结构

    今天是读《python算法教程》的第2天,读书笔记内容为用python实现图和树的基本数据结构。 图 图的基本数据...

  • 一直以来看Python会遇到数据结构的问题,因为非科班出身,对于数据结构的基础知识很欠缺,之前看了些树,但仍然是似...

  • 树 - 树和二叉树基础

    之前我们学过的数据结构都是线性数据结构,而树是我们学习的第一个非线性数据结构。 树 “树”这个数据结构的名字非常形...

  • 用Python实现二叉树的增、删、查

    日拱一卒,每周为你带点 Python 干货。 学过数据结构的同学一定这种数据结构非常熟悉了,树是一种非常高效的非线...

网友评论

      本文标题:python数据结构-树

      本文链接:https://www.haomeiwen.com/subject/bolfrxtx.html