一旦我们遇到气泡以后,就不可以再碰到任何数字。所以设置一个boolean变量flag,当遇到null时就设置成true,以后如果再遇到数字就return false。代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isCompleteTree(TreeNode root) {
if(root == null){
return true;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean flag = false;
while(!queue.isEmpty()){
TreeNode curr = queue.poll();
if(curr.left == null){
flag = true;
}else if(flag){
return false;
}else{
queue.offer(curr.left);
}
if(curr.right == null){
flag = true;
}else if(flag){
return false;
}else{
queue.offer(curr.right);
}
}
return true;
}
}