数据结构之树与二叉树

满二叉树与完全二叉树

满二叉树:

如果一棵二叉树只有度为0的结点和度为2的结点,并且度为0的结点在同一层上,则这棵二叉树为满二叉树。如下图所示:
在这里插入图片描述

完全二叉树

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^(h-1) 个节点。

在这里插入图片描述

代码

'''
#模拟文件系统

class Node:
    def __init__(self,name,type='dir'):
        self.name=name
        self.type=type
        self.children=[]
        self.parent=None
    def __repr__(self):
        return self.name

n=Node('hello')
n2=Node('world')
n.children.append(n2)
n2.parent=n

class FileSystemTree:
    def __init__(self):
        self.root=Node('/')
        self.now=self.root      #now指的是当前文件夹


    #创建文件夹
    def mkdir(self,name):
        #name以/结尾
        if name[-1]!='/':
            name+='/'
        node=Node(name)
        self.now.children.append(node)
        node.parent=self.now

    #展示当前目录下的所有文件夹
    def ls(self):
        return self.now.children

    #切换目录
    def cd(self,name):
        if name[-1]!='/':
            name+='/'

        if name=='../':
            self.now=self.now.parent
            return

        for child in self.now.children:
            if child.name==name:
                self.now=child
                return

        raise ValueError('invalid dir')


tree=FileSystemTree()
tree.mkdir('var/')
tree.mkdir('bin/')
tree.mkdir('usr/')

tree.cd('bin/')
tree.mkdir('python/')
print(tree.ls())

'''

'''构建二叉树'''

class BiTreeNode:
    def __init__(self,data):
        self.data=data
        self.lchild=None
        self.rchild=None
        self.parent=None

a=BiTreeNode("A")
b=BiTreeNode("B")
c=BiTreeNode("C")
d=BiTreeNode("D")
e=BiTreeNode("E")
f=BiTreeNode("F")
g=BiTreeNode("G")

e.lchild=a
e.rchild=g
a.rchild=c
c.lchild=b
c.rchild=d
g.rchild=f

root=e
# print(root.lchild.rchild.data)


'''二叉树的遍历'''
#前序遍历
def pre_order(root):
    if root:        #递归终止条件
        print(root.data,end=',')
        pre_order(root.lchild)
        pre_order(root.rchild)

print('前序遍历',end=':')
pre_order(e)

#中序遍历
def in_order(root):
    if root:
        in_order(root.lchild)
        print(root.data,end=",")
        in_order(root.rchild)
print()
print('中序遍历',end=':')
in_order(root)

#后序遍历
def post_order(root):
    if root:
        post_order(root.lchild)
        post_order(root.rchild)
        print(root.data,end=',')
print()
print('后序遍历',end=':')
post_order(root)

from collections import deque


#层次遍历
def level_order(root):
    queue=deque()
    queue.append(root)
    while len(queue)>0:
         node=queue.popleft()
         print(node.data,end=',')
         if node.lchild:
            queue.append(node.lchild)
         if node.rchild:
             queue.append(node.rchild)

print()
print('层次遍历',end=':')
level_order(root)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值