检测是否为二叉搜索树

题目描述:

给定一个树状结构(可能不是树),检查它是否是二叉搜索树。如果答案为YES,则输出“YES”及其叶子节点总数;否则,输出“NO”。

输入:

  • 第一行:1个数字 n

  • 以下n几行:每行包含两个值xy,表示具有 key 的节点是具有 key 的节点x的父节点y。第一个y是 的左孩子x,第二个y是 的右孩子x。如果y-1,则没有 的对应子代x。请注意,树中所有节点的键都是不同的且为正的。

输出:

  • 如果输入树是二叉搜索树,则输出“YES”及其叶子节点总数;否则,输出“NO”。

代码如下:

import java.util.*;

public class T {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int nums = in.nextInt(),index = 1;
        if (nums <= 0){
            System.out.println("NO");
            return;
        }
        int[] tree = new int[(int) Math.pow(4*nums,2)];
        Map<Integer,Integer> map = new HashMap<>();
        Map<Integer,Integer> count = new HashMap<>();
        Map<Integer,Integer> res = new HashMap<>();
        while (nums > 0){
            int x = in.nextInt();
            int y = in.nextInt();
            index = map.getOrDefault(x,1);
            tree[index] = x;
            map.put(x,index);
            if (count.getOrDefault(x,0) > 2 && res.containsKey(y)){
                System.out.println("NO");
                return;
            }else {
                count.put(x,count.getOrDefault(x,0)+1);
            }
            res.put(y,0);
            if(count.getOrDefault(x,0) == 1){
                tree[index * 2 ] = y;
                map.put(y,index*2);
            }else {
                tree[index * 2+1] = y;
                map.put(y,index*2+1);
            }
            nums--;
        }
        if(isValidBST(tree,1,Long.MIN_VALUE, Long.MAX_VALUE)){
            System.out.println("YES "+countLeaf(tree,1));
        }else {
            System.out.println("NO");
        }
        in.close();
    }



    /**
     * 求二叉树的叶子数
     * @param tree
     * @return
     */
    public static int countLeaf(int[] tree,int index){
        if (tree[index] <= 0){
            return 0;
        }
        if (tree[index*2]<=0 && tree[index*2+1]<=0){
            return 1;
        }
        return countLeaf(tree,index*2) + countLeaf(tree,index*2+1);
    }

    /**
     * 判断二叉树是否为二叉搜索树
     * @param tree
     * @param index
     * @param lower
     * @param upper
     * @return
     */
    public static boolean isValidBST(int[] tree,int index, long lower, long upper) {
        if (tree[index] <= 0) {
            return true;
        }
        if (tree[index] <= lower || tree[index] >= upper) {
            return false;
        }
        return isValidBST(tree,index*2, lower, tree[index]) && isValidBST(tree,index*2+1, tree[index], upper);
    }



}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值