115th LeetCode Weekly Contest Check Completeness of a Binary Tree
2024-08-25 00:30:05
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:
- 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;
}
}
最新文章
- PHP 关于SQL注入的防范措施。
- FastDFS----recovery状态问题排查记录
- 并发编程中.net与java的一些对比
- 纪念逝去的岁月——C/C++字符串反转
- Go语言_时间篇
- Shell获取当前用户
- vpn连接成功后,本地无法连接外网
- struts2.1笔记05:struts2开发环境的搭建
- axis2 调用.net基于https的WebService接口
- 【问题】Win7 系统下 Firefox hostadmin插件无法修改Host
- REST Web Server,REST介绍
- 9.session的生命周期
- CentOS7中安装MySQL5.7 (转)
- Http_4个新的http状态码:428、429、431、511
- mac 10.12 sierra 机械键盘+ratm可编程鼠标记录
- jquery.validate和jquery.form配合实现验证表单后AJAX提交
- jdk和cglib简单理解
- Luogu P2827 蚯蚓
- windows和linux文件的转换
- GitHub笔记(二)——远程仓库的操作
热门文章
- 69. Sqrt(x) 求根号再取整
- grid search 超参数寻优
- Python3 常用爬虫库的安装
- 面向对象property属性、静态方法和类方法
- VMWare、Ubuntu Server 18.04 共享文件夹
- ASP.NET MVC5 Authentication Filters执行链
- HDU 1540 Tunnel Warfare (线段树或set水过)
- Entity Framework快速入门--直接修改(简要介绍ObjectContext处理机制)
- MVC 基本概念
- webrequest、httpwebrequest、webclient、HttpClient 四个类的区别