题解 | #判断是不是完全二叉树# DFS递归 BFS队列
判断是不是完全二叉树
https://www.nowcoder.com/practice/8daa4dff9e36409abba2adbe413d6fae
- 深度优先用递归
- 广度优先用循环队列(一边出一边入)
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param root TreeNode类
# @return bool布尔型
#
class Solution:
def isCompleteTree(self , root: TreeNode) -> bool:
if root is None:
return True
l = [root]
# 是否遇到空节点
f = False
while len(l) > 0:
now = l.pop(0)
# 遇到空节点就记录下
if now is None:
f = True
else:
# 遇到之后还有不是空节点的就不是完全二叉树
if f: return False
l.append(now.left)
l.append(now.right)
return True
查看12道真题和解析