python设计算法判断一棵树是否为完全二叉树附带测试结果
时间: 2024-04-29 08:26:00 浏览: 8
好的,我明白了。针对您的问题,可以利用完全二叉树的性质进行判断。完全二叉树的性质包括:除了最底层节点外,其余层节点数都要达到最大值,最底层上的节点集中在树的左边连续位置上。具体的算法实现如下:
1.对树进行层序遍历(BFS),同时记录每个节点的编号。
2.如果当前节点没有右子节点但是有左子节点(左枝膀不空,右枝膀空了),那么就不是完全二叉树。
3.如果当前节点的编号为i(从1开始),但左子节点的编号不为2i,那么也不是完全二叉树。
4.如果当前节点的编号为i(从1开始),右子节点的编号不为2i+1,也不是完全二叉树。
5.如果上述情况都没有出现,则为完全二叉树。
下面是实现的Python代码,并且附带了一组测试结果:
```python
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isCompleteTree(root: Node) -> bool:
if not root:
return True
nodes = [(root, 1)]
i = 0
while i < len(nodes):
curr_node, curr_idx = nodes[i]
i += 1
if curr_node:
nodes.append((curr_node.left, curr_idx*2))
nodes.append((curr_node.right, curr_idx*2+1))
return nodes[-1][1] == len(nodes)
# testing
root1 = Node(1, Node(2, Node(4), Node(5)), Node(3, Node(6)))
root2 = Node(1, Node(2, Node(4), Node(5)), Node(3))
root3 = Node(1, Node(2, Node(4)), Node(3, Node(5), Node(6)))
print(isCompleteTree(root1)) # True
print(isCompleteTree(root2)) # True
print(isCompleteTree(root3)) # False
```
希望这个代码对您有所帮助!