回复 楼主 Ⅳ飒
我答第二题
class Node(object):
def __init__(self, elem=-1, lchild=None, rchild=None):
self.elem = elem
self.lchild = lchild
self.rchild = rchild
def trans(a,i,n): #n是以顺序存储元素个数
if (i>n):
return None
b=Node(a[i-1])
if b.elem=='#':
return None
b.lchild=trans(a,2*i,n)
b.rchild=trans(a,2*i+1,n)
return b
def isCBTree(root):
if not root:
return False
queue = [root]
result = True
hasNoChild=False
while queue:
cur=queue.pop(0)
if hasNoChild:
if cur.lchild or cur.rchild:
return False
break
else:
if cur.lchild and cur.rchild:
queue.append(cur.lchild)
queue.append(cur.rchild)
elif cur.lchild and not cur.rchild:
queue.append(cur.lchild)
hasNoChild=True
elif not cur.lchild and cur.rchild:
result=False
break
else:
hasNoChild=True
return result
if __name__=='__main__':
a=input('请以顺序存储的方式输入二叉树,用#补成满二叉树:')
n=len(a)
cc=isCBTree(trans(a,1,n))
if cc==True:
print('此二叉树是完全二叉树')
else:
print('此二叉树不是完全二叉树')