L958. 二叉树的完全性检验 java

  1. 从1开始当下标,最后节点下标==节点总数?true:false;
java 复制代码
/**
 * 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 {
    int size=0,maxs=0;
    public boolean isCompleteTree(TreeNode root) {
        if(root==null) return  true;
        func(root,1);
        return size==maxs;
    }
    public void func(TreeNode node , int index){
        if(node==null) return ;
        size++;
        maxs=Math.max(maxs,index);   
        func(node.left,2*index);
        func(node.right,1+2*index);
   


    }
}
  1. 标准BFS,层序遍历,出现空节点后再出现非空节点就不是,其他都是。
java 复制代码
/**
 * 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 {
    int size=0,maxs=0;
    public boolean isCompleteTree(TreeNode root) {
        if(root==null) return true;
        int cnt=0;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            TreeNode cur= q.poll();
            if(cur==null) cnt=1;
            else{
                if(cnt==1) return false;
                q.offer(cur.left);
                q.offer(cur.right);
            }
        }
        return  true;
    }
}
相关推荐
virus594535 分钟前
悟空CRM mybatis-3.5.3-mapper.dtd错误解决方案
java·开发语言·mybatis
一匹电信狗40 分钟前
【LeetCode_547_990】并查集的应用——省份数量 + 等式方程的可满足性
c++·算法·leetcode·职场和发展·stl
鱼跃鹰飞1 小时前
Leetcode会员尊享100题:270.最接近的二叉树值
数据结构·算法·leetcode
Queenie_Charlie1 小时前
小陶的疑惑2
数据结构·c++·树状数组
没差c2 小时前
springboot集成flyway
java·spring boot·后端
时艰.2 小时前
Java 并发编程之 CAS 与 Atomic 原子操作类
java·开发语言
梵刹古音2 小时前
【C语言】 函数基础与定义
c语言·开发语言·算法
编程彩机2 小时前
互联网大厂Java面试:从Java SE到大数据场景的技术深度解析
java·大数据·spring boot·面试·spark·java se·互联网大厂
笨蛋不要掉眼泪2 小时前
Spring Boot集成LangChain4j:与大模型对话的极速入门
java·人工智能·后端·spring·langchain
筵陌3 小时前
算法:模拟
算法