第八关|二叉树深度问题

1、最大深度问题

leetcode104

1、法一:递归

与后序遍历类似,先算出左右子树的结果再进行相关操作。

    public static int maxDepth_1(TreeNode root) {

        if (root == null) return 0;

        int left = maxDepth_1(root.left);
        int right = maxDepth_1(root.right);

        return Math.max(left, right) + 1;

    }

2、法二:层次遍历法

在以层为单位操作时,每层操作结束,将层数+1。

与之前的层次遍历 类似。

    public static int maxDepth_2(TreeNode root) {

        if (root == null) return 0;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        int ans = 0;

        while (!queue.isEmpty()) {

            //一层个数
            int size = queue.size();

            //某层节点出队后,将它的下一层入队
            for (int i = 0; i < size; i++) {
                TreeNode tmp = queue.poll();
                if (tmp.left != null) {
                    queue.add(tmp.left);
                }
                if (tmp.right != null) {
                    queue.add(tmp.right);
                }
            }
            //层数++
            ans++;
        }
        return ans;
    }

2、判断平衡树

leetcode110

1、法一:自上而下

通过自上而下遍历每个节点,并且对每个节点的左右节点深度做对比。

    public static boolean isBalance_1(TreeNode root){

        if(root == null) return true;

        return Math.abs(maxDepth(root.left)-maxDepth(root.right)) < 2 && isBalance_1(root.left) && isBalance_1(root.right);

    }

    public static int maxDepth(TreeNode root){
        if(root == null) return 0;
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }

2、法二:自下而上

通过自下而上遍历每个节点,并且计算差值是否平衡,不平衡返回-1直到最上层,表示不平衡。

若某节点左右平衡,则把它的高度返回,以便上层节点计算差值。

    public static boolean isBalance_2(TreeNode root){
        return recur(root) != -1;
    }

    public static int recur(TreeNode root){

        if(root == null) return 0;

        int left = recur(root.left);
        if(left == -1) return -1;

        int right = recur(root.right);
        if(right == -1) return -1;

        return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值