满二叉树与完全二叉树
满二叉树:
如果一棵二叉树只有度为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)