题目
给定一个二叉树,确定他是否是一个完全二叉树。
完全二叉树的定义:若二叉树的深度为 h,除第 h 层外,其它各层的结点数都达到最大个数,第 h 层所有的叶子结点都连续集中在最左边,这就是完全二叉树。(第 h 层可能包含 [1~2h] 个节点)
思路
按照蹭层序遍历,将每个节点(包括空节点)依次放入队列中,如果在poll的时候有一个为空节点,下一个又不是空节点,那肯定不是完全二叉树
代码
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return bool布尔型
*/
public boolean isCompleteTree (TreeNode root) {
Queue<TreeNode>queue = new LinkedList<>();
// write code here
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node != null) {
if (node.left == null && node.right != null) {
return false;
} else {
queue.offer(node.left);
queue.offer(node.right);
}
} else {
break;
}
}
while(!queue.isEmpty()){
TreeNode poll=queue.poll();
if(poll!=null){
return false;
}
}
return true;
}
}