题解 | #判断一棵二叉树是否为搜索二叉树和完全二叉树#

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

https://www.nowcoder.com/practice/f31fc6d3caf24e7f8b4deb5cd9b5fa97

二叉搜索树:中序遍历有序;完全二叉树:节点集中在左侧

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布尔型一维数组
     */
    
    private TreeNode max = null;
    private boolean flag = false;

    public boolean[] judgeIt (TreeNode root) {
        // write code here
        // 判断之后的节点是否有小于已遍历结点的最大值
        // 完全二叉树:出现空的位置之后是否有节点
        // 递归三部曲:返回值boolean,参数:root; 返回值
        // 单层逻辑:存储最大值的max,判断当前是否小于max,false
        // 终结:null,返回true
        boolean[] result = new boolean[2];
        result[0] = binarySearch(root);
        result[1] = binaryPerfect(root);
        System.out.println(result[0]);
        System.out.println(result[1]);
        return result;
    }

    // 判断二叉搜索树 
    private boolean binarySearch(TreeNode root) {

        if (root == null) {
            return true;
        }
        
        boolean left = binarySearch(root.left);
        if (!left) {
            return false;
        }
        if (max != null && max.val > root.val) {
            return false;
        }
        max = root;

        return binarySearch(root.right);
    }

    // 使用广度优先搜索
    // 如果已设置标志位,但仍然出现非空情况,则返回false
    private boolean binaryPerfect(TreeNode root) {

        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return true;
        }
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();

            // 处理特殊情况
            if (flag && (node.left != null || node.right != null)) {
                return false;
            }

            if (node.left == null || node.right == null) {
                flag = true;
            }

            if (node.left == null && node.right != null) {
                return false;
            }

            if (node.left != null) {
                queue.offer(node.left);
            }

            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        return true;
    }
}

全部评论

相关推荐

昨天 10:54
华南理工大学
昨天收到腾讯音乐OC了,xdm,准备去做TME孝子了!正式宣布:TME,你的兵来了!BG:本硕都是华南理工软件工程专业,有腾讯CSIG和字节的两段实习,还有一篇A区论文一作在投。OC的是酷狗的后台开发。不为别的,就为这第一个OC,想哭!流程里还有团子和鹅,上周被阿里一轮游了……脆皮大学生表示:淘宝已卸载,谢谢。广州人,就想找个离家近的厂,当然也有自己的一些考虑,放在最后,兄弟们要是没有精力海投或者最后要抉择Offer,可以参考我的逻辑。TL:3.14网申-3.17一面-3.19二面-3.21&nbsp;hr面-3.24OC。TME没有笔试,我就面试的时候手撕了一轮,所以感觉流程推进很快,刚好10天,顺利...
都有实习了:10天速通?恭喜大佬,而且真的好厉害 但是有一个***********************诉你,根本没人问你,在我们之中0人问了你,我把所有问你的人都请来 party 了,到场人数是0个人,誰问你了?WHO ASKED?谁问汝矣?誰があなたに聞きましたか?누가 물어봤어?我爬上了珠穆朗玛峰也没找到谁问你了,我刚刚潜入了世界上最大的射电望远镜也没开到那个问你的人的盒,在找到谁问你之前我连癌症的解药都发明了出来,我开了最大距离渲染也没找到谁问你了我活在这个被辐射蹂躏了多年的破碎世界的坟墓里目睹全球核战争把人类文明毁灭也没见到谁问你了(别的帖子偷来的,现学现卖哈哈)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务