原题链接在这里:https://leetcode.com/problems/check-completeness-of-a-binary-tree/

题目:

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.

题解:

Perform level order traversal on the tree, if popped node is not null, then add its left and right child, no matter if they are null or not.

If the tree is complete, when first met null in the queue, then the rest should all be null. Otherwise, it is not complete.

Time Complexity: O(n).

Space: O(n).

AC Java:

 /**
* 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) {
LinkedList<TreeNode> que = new LinkedList<TreeNode>();
que.add(root);
while(que.peek() != null){
TreeNode cur = que.poll();
que.add(cur.left);
que.add(cur.right);
} while(!que.isEmpty() && que.peek() == null){
que.poll();
} return que.isEmpty();
}
}

类似Complete Binary Tree Inserter.

最新文章

  1. 关于WEB Service&amp;WCF&amp;WebApi实现身份验证之WCF篇(2)
  2. [ACM_搜索] ZOJ 1103 || POJ 2415 Hike on a Graph (带条件移动3盘子到同一位置的最少步数 广搜)
  3. drupal7 Views Slideshow 简单教程
  4. ODI中显示us7ascii字符集的测试
  5. poj 2299 树状数组求逆序对数+离散化
  6. hotfix分析
  7. (转)iOS中3种正则表达式的使用与比较
  8. Request.url用法
  9. PHP curl 常用操作
  10. Chapter 5 Blood Type——31
  11. vue-cli教程
  12. dubbo入门学习 六 admin管理界面
  13. 吴恩达课后作业学习2-week1-1 初始化
  14. 基础语言知识JAVA
  15. 20155216 2016-2017-2 《Java程序设计》第三周学习总结
  16. centos6.5安装cmake-gui
  17. WebFrom页面绑定数据过于冗长的处理方法
  18. Android(java)学习笔记56:Android InputMethodManager输入法简介
  19. Reference resources
  20. 个人博客开发之 全局配置文件settings设置

热门文章

  1. JAVA知识点总结篇(二)
  2. Linux下嵌入式Web服务器BOA和CGI编程开发
  3. SPOJ Qtree系列
  4. golang基础学习-strings包常用函数学习
  5. git学习笔记 ---添加远程库
  6. 记一次线上问题排查:C#可选参数的坑
  7. linux 流量监控利器:iftop
  8. IntelliJ IDEA web项目进行数据库连接时出现java.lang.ClassNotFoundException: com.mysql.jdbc.Driver错误解决办法
  9. SAP错误消息调试之七种武器:让所有的错误消息都能被定位
  10. WebApi中将静态页面作为首页