NC60 判断一棵二叉树是否为搜索二叉树和完全二叉树

该博客提供了一个Java解决方案,用于检查给定的二叉树是否同时满足搜索二叉树(BST)和完全二叉树(CBT)的条件。它通过递归函数实现,分别对BST和CBT进行判断,确保每个节点的值在子树范围内,并检查CBT的每一层节点填充情况。

NC60 判断一棵二叉树是否为搜索二叉树和完全二叉树

描述
给定一棵二叉树,已知其中的节点没有重复值,请判断该二叉树是否为搜索二叉树和完全二叉树。
示例1
输入:
{2,1,3}
复制
返回值:
[true,true]

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 the root
     * @return bool布尔型一维数组
     */
    public boolean[] judgeIt (TreeNode root) {
        // write code here
        boolean[] res = new boolean[2];
        res[0] = isBST(root);
        res[1] = isCBT(root);
        return res ;
    }
    public boolean isBST(TreeNode root){
        boolean r = BSThelper(root , Long.MIN_VALUE , Long.MAX_VALUE) ;
        return r;
    }
    public boolean BSThelper(TreeNode root , long max , long min){
        if(root == null){
            return true;
        }
        if(root.val <= max || root.val > min){
            return false ;
        }
        return BSThelper(root.left , max , Math.min(root.val , min)) && BSThelper(root.right , Math.max(max , root.val) , min);
    }
    public boolean isCBT(TreeNode root){
        if(root == null){
            return false ;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root) ;
        while(!queue.isEmpty()){
            TreeNode node = queue.peek();
            if(node.left != null && node.right != null){
                queue.poll();
                queue.offer(node.left);
                queue.offer(node.right);
            }
            if(node.left == null && node.right != null){
                return false ;
            }
            if((node.left != null && node.right == null) || (node.left == null && node.right == null)){
                queue.poll();
                while(!queue.isEmpty()){
                    node = queue.peek();
                    if(node.left == null && node.right == null){
                        queue.poll();
                    }else{
                        return false ;
                    }
                }
            }
        }
        return true ;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值