Given a binary tree, determine if it is a complete binary tree.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Example 1:

Input: [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.

Example 2:

Input: [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
 

Note:

  1. The tree will have between 1 and 100 nodes.

常规题

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isCompleteTree(TreeNode root) {
if(root == null)
return true;
Queue<TreeNode>queue = new LinkedList<>();
boolean leaf = false; //如果碰到了 某个结点孩子不全就开始 判断是不是叶子这个过程
queue.add(root);
TreeNode top = null,L = null,R = null;
while(!queue.isEmpty()){
top = queue.poll();
L = top.left; R = top.right;
//第一种情况
if((R != null && L == null))
return false;
//第二种情况 开启了判断叶子的过程 而且又不是叶子 就返回false
if(leaf && (L != null || R != null)) //以后的结点必须是 左右孩子都是null
return false; if(L != null)
queue.add(L); //准确的说是 只要孩子不全就开启leaf,
//但是前面已经否定了有右无左的情况,这里只要判断一下右孩子是不是为空就可以了(如果为空就开启leaf)
if(R != null)
queue.add(R);
else
leaf = true;
}
return true;
}
}

最新文章

  1. PHP 关于SQL注入的防范措施。
  2. FastDFS----recovery状态问题排查记录
  3. 并发编程中.net与java的一些对比
  4. 纪念逝去的岁月——C/C++字符串反转
  5. Go语言_时间篇
  6. Shell获取当前用户
  7. vpn连接成功后,本地无法连接外网
  8. struts2.1笔记05:struts2开发环境的搭建
  9. axis2 调用.net基于https的WebService接口
  10. 【问题】Win7 系统下 Firefox hostadmin插件无法修改Host
  11. REST Web Server,REST介绍
  12. 9.session的生命周期
  13. CentOS7中安装MySQL5.7 (转)
  14. Http_4个新的http状态码:428、429、431、511
  15. mac 10.12 sierra 机械键盘+ratm可编程鼠标记录
  16. jquery.validate和jquery.form配合实现验证表单后AJAX提交
  17. jdk和cglib简单理解
  18. Luogu P2827 蚯蚓
  19. windows和linux文件的转换
  20. GitHub笔记(二)——远程仓库的操作

热门文章

  1. 69. Sqrt(x) 求根号再取整
  2. grid search 超参数寻优
  3. Python3 常用爬虫库的安装
  4. 面向对象property属性、静态方法和类方法
  5. VMWare、Ubuntu Server 18.04 共享文件夹
  6. ASP.NET MVC5 Authentication Filters执行链
  7. HDU 1540 Tunnel Warfare (线段树或set水过)
  8. Entity Framework快速入门--直接修改(简要介绍ObjectContext处理机制)
  9. MVC 基本概念
  10. webrequest、httpwebrequest、webclient、HttpClient 四个类的区别