23.二叉树的最小深度

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

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

说明:叶子节点是指没有子节点的节点。
解题思路
标签:DFS
终止条件、返回值和递归过程:
当前节点 root 为空时,说明此处树的高度为 0,0 也是最小值
当前节点 root 的左子树和右子树都为空时,说明此处树的高度为 1,1 也是最小值
如果为其他情况,则说明当前节点有值,且需要分别计算其左右子树的最小深度,返回最小深度 +1,+1 表示当前节点存在有 1 个深度
时间复杂度:O(n)O(n),nn为树的节点数量
*/
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        int ans = Integer.MAX_VALUE;
        if(root.left != null) {
            ans = Math.min(minDepth(root.left), ans);
        }
        if(root.right != null) {
            ans = Math.min(minDepth(root.right), ans);
        }
        return ans + 1;
    }
}

 

posted @ 2022-03-11 09:47  随遇而安==  阅读(26)  评论(0编辑  收藏  举报