leetcode——求二叉树的最大(小)深度

最大深度:从根节点到叶子节点的最长路径上的节点个数
在这里插入图片描述
最大深度为3
规则:
(1)二叉树为空,返回0
(2)递归计算左孩子和右孩子的深度,取最大值+1

代码实现

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int run(TreeNode root) {
        if(root == null)   return 0;
        return Math.max(run(root.left),run(root.right))+1;
    }
}

**最小深度:**从根节点到叶子节点的最短路径所经过的节点个数
在这里插入图片描述
最小深度为2
规则:
(1)二叉树为空,返回0
(2)如果二叉树没有右(左)孩子,则二叉树最小深度 = 左(右)孩子深度+1

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int run(TreeNode root) {
        if(root == null) return 0;
        else if(root.left == null) return run(root.right)+1;
        else if(root.right == null) return run(root.left)+1;
        return Math.min(run(root.left),run(root.right))+1;   
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42937036/article/details/105280961
今日推荐