二叉树的深度

85 阅读2分钟

二叉树的最大深度

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

分析:二叉树一般都可以用递归来实现,关键是递归截止的条件,显然这个截止条件是当节点为空时,返回0

很好,感觉很简单,来写代码😁:

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

那为什么没有其他的判断条件呢?

比如root.right == null的情况下,为什么没有呢?

因为如果右边的节点为null,就是返回的是左边的最大深度+1,同理

但其实被包括在了Math.max(maxDepth(root.left),maxDepth(root.right))+1;这个里面,这样就好说了,

那么来进阶一下:😜😜😜

二叉树的最小深度

给定一个二叉树,找出其最小深度。

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

说明: 叶子节点是指没有子节点的节点。

分析:同理使用递归来实现,那能不能这样写:

 class Solution {
     public int minDepth(TreeNode root) {
         if(root==null){
             return 0;
         }
         return Math.min(minxDepth(root.left),minDepth(root.right))+1;
     }
 }

不能这样写,这种就是没有理解题干,最小深度是从根节点到最近叶子节点的最短路径上的节点数量,所以在中间的节点,root.right == null时,返回的是0吗?不是,应该是什么呢?

分析:这个中间的节点的root.right == null,那么最小深度是这个子节点也就是另一个节点的最小深度加1

         if (root.right == null) {
             return minDepth(root.left) + 1;
         }

很好😁😁😁

到这里就会发现,最小深度的处理,要处理这个节点是不是叶子节点,分几种情况:

根节点root是叶子节点,那么返回最小深度为1

根节点root不是叶子节点,那么还分两种情况:

第一种:左孩子或者有孩子有一个为null,那么最小深度是这个子节点的最小深度加1

第二种:有两个孩子,取左右子树最小深度的较大值加1

开写代码:

 class Solution {
     public int minDepth(TreeNode root) {
         if (root == null) {
             return 0; // 空树的最小深度为0
         }
         // 如果根节点是叶子节点,最小深度为1
         if (root.left == null && root.right == null) {
             return 1;
         }
         // 如果根节点只有一个子节点,最小深度是这个子节点的最小深度加1
         if (root.left == null) {
             return minDepth(root.right) + 1;
         }
         if (root.right == null) {
             return minDepth(root.left) + 1;
         }
         // 如果根节点有两个子节点,取左右子树最小深度的较大值加1
         return Math.max(minDepth(root.left), minDepth(root.right)) + 1;
     }
 }

完结撒花,好好分析一下不难💕💕💕