[二叉树]111. Minimum Depth of Binary Tree

题目:111. Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

DFS的题。

注意必须是root-leaf的长,即如果root只有右子树,那么最小深度就是右子树深度,不是0(左子树深度)。所以比较左右深度,只在子树不为0时才比较,否则就是INT最大VALUE。

第一次提交: min是global var,

class Solution {
    //必须是root-leaf的长
    int min;
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        return Math.min(Integer.MAX_VALUE, countDepth(root, 0));
    }
    
    private int countDepth(TreeNode root, int count){
        count++;
        if(root.left == null && root.right == null){
            return count;
        }
        int left = Integer.MAX_VALUE;
        int right = Integer.MAX_VALUE;
        if(root.left != null)  left = countDepth(root.left, count);
        if(root.right != null) right = countDepth(root.right, count);
        min = Math.min(left, right);
        return min;

    }
}

写完发现可以不需要int min。

class Solution {
    //必须是root-leaf的长
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        return Math.min(Integer.MAX_VALUE, countDepth(root, 0));
    }
    
    private int countDepth(TreeNode root, int count){
        count++;
        if(root.left == null && root.right == null){
            return count;
        }
        int left = Integer.MAX_VALUE;
        int right = Integer.MAX_VALUE;
        if(root.left != null)  left = countDepth(root.left, count);
        if(root.right != null) right = countDepth(root.right, count);
        return  Math.min(left, right);

    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容