• 算法通过村第八关-树(深度优先)白银笔记|深度和高度问题



    前言


    提示:我的整个生命,只是一场为了提升社会地位的低俗斗争。--埃莱娜·费兰特《失踪的孩子》

    这一关我们看一些比较特别的题目,关于二叉树的深度和高度问题。这些对递归的考察更高些,要注意了。

    给你一个二叉树:
    在这里插入图片描述
    我们看下力扣的相关题目,这些是关于深度和高度的问题。

    推荐题目⭐⭐⭐⭐:

    104. 二叉树的最大深度 - 力扣(LeetCode)

    110. 平衡二叉树 - 力扣(LeetCode)

    111. 二叉树的最小深度 - 力扣(LeetCode)

    1. 最大深度问题

    参考题目介绍:104. 二叉树的最大深度 - 力扣(LeetCode)
    在这里插入图片描述
    在这里插入图片描述
    首先最大深度:根节点到最远叶子节点的最长路径上的节点数。说明叶子节点是没有子节点的。

    我们看看下面这些。(上图的最大深度为3)

    在这里插入图片描述
    对于node(3),最大深度自然是左右子节点+1,左右子节点有可能为空,只要有一个,树的最大高度就是1 + 1 = 2。然后再增加几个节点:
    在这里插入图片描述
    很显然相对于node(20),最大的深度自然是左右子节点+1,左右子节点有可能为空,只要右一个,树的最大高度就是1 + 1 = 2,用代码表示就是:

    int depth = 1 + math(leftDepth,rightDepth);
    
    • 1

    对于3,则是左右子树深度最大的那个再加1,具体谁的更大,则不必管旭,所以对于node(3)的逻辑判断就是:

    int leftDepth =  getDepth(root.left); //左
    int rightDepth =  getDepth(root.right); // 右
    int depth = 1 + math(leftDept,rightDept); // 中
    
    • 1
    • 2
    • 3

    那么什么时候结束呢?这里仍然是root == null 返回0就行了,至于入参,自然是要处理的子树的根节点root,而返回值则是当前root所在子树的最大高度,所以合在一起就是:

    	/**
         * 通过递归计算二叉树的深度
         *
         * @param root
         * @return
         */
        public static int maxDepth_1(TreeNode root) {
            if(root == null) {
                return 0;
            }
            int leftDepth = maxDepth_1(root.left);
            int rightDepth = maxDepth_1(root.right);
            return Math.max(leftDepth, rightDepth) + 1;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    上面代码先拿到左右子树的结果,再计算Math.max(left,right) + 1,本质上和后序遍历一样,一次者可以看做事后序遍历的扩展问题。

    我们继续看这个题目,如果我们确定树最大有几层是不是也确定了最大深度呢?当然,另一个思路不就来了,我们直接套用层序遍历的代码:
    在这里插入图片描述
    具体细节注意一下:我们这里获取层数,每获取一层,就加一。

        /**
         * 通过层次遍历来求最大深度
         *
         * @param root
         * @return
         */
        public static int maxDepth_2(TreeNode root) {
            // 校验参数
            if (root == null){
                return 0;
            }
            // 创建空间
            int res = 0;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            // 根节点入队,不断的遍历根节点
            queue.offer(root);
            while(!queue.isEmpty()){
                // 获取到每层多少个
                int size = queue.size();
                //	size == 0 说明这一层遍历完了
                while(size > 0){
                    // 遍历
                    TreeNode node = queue.poll();
                    if (node.left != null){
                        queue.offer(node.left);
                    }
                    if (node.right != null){
                        queue.offer(node.right);
                    }
                    size--;
                }
                res++;
            }
            return res;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    2. 判断平衡树

    参考题目介绍:110. 平衡二叉树 - 力扣(LeetCode)

    在这里插入图片描述
    在这里插入图片描述
    补充一个知识点:高度和深度怎么区分?

    • 二叉树节点的深度:从根节点到该节点的最长简单路径边的条数。
    • 二叉树节点的高度:从该节点到叶子节点的最长简单路径边的条数。

    在这里插入图片描述
    关于根节点的深度是1还是0的问题,不同的地方标准不一样,力扣的题目中都是以根节点的深度为1,其他的我们先不管。

    我们接着看一下这个问题:

    在这里插入图片描述
    很显然只要有两次的时候一定是平衡的,因为对于node(3),左右孩子如果只有一个,呢么高度差就是1;如果左右孩子都没有或者都有,则高度差为0。但是如果再加一层呢?

    看下图:

    在这里插入图片描述
    对于node(3),需要同时知道自己左右子树的最大高度差是否< 2.

    • 当节点root左/右子树的高度差 < 2,则返回节点root的左右子树中最大高度+1(max(left,right) + 1);参考上面的深度和高度对比图思考下,这里为什么取最大高度?
    • 当节点root左/右子树的高度差 >= 2;则返回-1,代表此树已经不是平衡树了。

    也是就是说:

    int left = recur(root.left);
    int right = recur(root.right);
    return Math.abs(left - right) < 2 ? Math.max(left,right) + 1:-1; 
    
    • 1
    • 2
    • 3

    我们此时已经写出了核心代码,假设子树已经不平衡了,我们就不需要再递归下去而是直接返回就行了。例如这个树中的节点20:
    在这里插入图片描述
    综合考虑几种情况,我们看下完整的代码:

    	/**
         * 方法1 自下而上
         *
         * @param root
         * @return
         */
        public static boolean isBalanced_1(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;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    /**
         * 2.自上而下
         *
         * @param root
         * @return
         */
        public static boolean isBalanced_2(TreeNode root) {
            if (root == null){
                return true;
            }
            return Math.abs(depth(root.left) - depth(root.right)) <= 1 && isBalanced_2(root.left) && isBalanced_2(root.right);
        }
        public static int depth(TreeNode root){
            if (root == null){
                return 0;
            }
            return Math.max(depth(root.left),depth(root.right)) + 1;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    3. 最小深度

    参考题目介绍:111. 二叉树的最小深度 - 力扣(LeetCode)

    在这里插入图片描述
    在这里插入图片描述
    既然有最大深度,可能会有最小深度?这不他就来了,怎么找出最小深度呢?

    最小深度:从根节点到最接近叶子节点的最短路径上的节点数量。

    看下下面这个特殊例子: 答案是 2 【说明】:叶子节点是指没有子节点的节点。
    在这里插入图片描述
    前面两道题涉及到最大深度,这里讲max改成min是不是就可以解决了呢? 不行,你注意看上图:

    这里的关键问题是题目中说的:最小深度是从根节点到最近叶子节点的最短路径上的节点数量,也就是说最小深度的一层必须要有叶子节点,不能直接使用。

    这里的核心问题仍然是终止条件分析:

    • 如果左子树为空,右子树不为空,说明最小深度是1 + 右子树的深度。
    • 反之,右子树为空,左子树不为空,最小深度1 + 左子树的深度。

    最后如果左右子树都不空,返回左右子树深度最小值+1。

    我们看下代码展示😎:

    	/**
         * 通过递归计算二叉树的最小
         *
         * @param root
         * @return
         */
        public static int minDepth_1(TreeNode root) {
           if (root == null){
               return 0;
           }
            // 根
           if (root.left == null && root.right == null){
               return 1;
           }
            // 左
           int min_depth = Integer.MAX_VALUE;
           if (root.left != null){
               min_depth = Math.min(minDepth_1(root.left),min_depth);
           }
           // 右
           if (root.right != null){
               min_depth = Math.min(minDepth_1(root.right),min_depth);
           }
           return min_depth + 1;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    除了递归方式,我们也可以采用层次遍历,只要再遍历时,第一次遇到叶子节点就直接返回,其所在的层次就行,我们可以简单改下层序遍历的方法:

    	/**
         * 通过层次遍历来求最大深度
         *
         * @return
         */
        public static int minDepth_2(TreeNode root) {
            // 参数检验
            if (root == null){
                return 0;
            }
            // 创建空间
            int minDepth = 0;
            Queue<TreeNode> queue = new LinkedList<>();
            // 根节点入队,不断循环遍历
            queue.offer(root);
            while(!queue.isEmpty()){
                // 获取队列的长队  这个长度说明这一层有多少个节点
                int size = queue.size();
                minDepth++;
                for(int i = 0; i < size; i++){
                    TreeNode node = queue.poll();
                    if (node.left == null && node.right == null){
                        return minDepth;
                    }
                    if (node.left != null){
                        queue.offer(node.left);
                    }
                    if (node.right != null){
                        queue.offer(node.right);
                    }
                }
            }
            return 0;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    4. N叉树的最大深度

    参考题目介绍:559. N 叉树的最大深度 - 力扣(LeetCode)

    在这里插入图片描述
    在这里插入图片描述
    这道题不同的地方是将二叉树换成了N叉树,N叉树的节点较多,我们使用List存储,遍历时采用for即可,我们先看看力扣的N叉树的定义:

    class Node {
        public int val;
        public List<Node> children;
    
        public Node() {}
    
        public Node(int _val) {
            val = _val;
        }
    
        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    这个题的实现和上个题的最大区别就是在处理子树的问题上面加了个处理List的for循环

    代码也很简单🤔:

    	/**
         * 递归求N叉树的深度
         * @param root
         * @return
         */
        public static int maxDepth_N(NTreeNode root) {
           if (root == null){
               return 0;
           }else if (root.children.isEmpty()){
                return 1;
           }else{
               // 处理子树问题
               List<Integer> heights = new ArrayList<>();
               for(NTreeNode item : root.children){
                   heights.add(maxDepth_N(item));
               }
               return Collections.max(heights) + 1;
           }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    当然了,本地还可以使用层序遍历,这个作为拓展感兴趣的话可以试试。


    总结

    提示:二叉树的深度和高度;N叉树的深度问题;平衡树的判断问题

  • 相关阅读:
    面试经典刷题)挑战一周刷完150道-Python版本-第2天(22个题)
    AIGC之文本内容生成概述(下)—— GPT
    一文带你看透手机号码归属地
    报错大赏(9.11-9.18)
    Sprites and textures
    node.js学习笔记 10包管理器
    【第六章】集合类:List、Iterator迭代器
    【Java】FileUtils练习题3
    leetcode:33.搜索旋转排序数组
    PLL锁相环设计中的VCXO性能权衡
  • 原文地址:https://blog.csdn.net/weixin_46585492/article/details/132985869