【74.二叉树的最小深度】

58 阅读1分钟

题目

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

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

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

示例 1:

输入: root = [3,9,20,null,null,15,7]
输出: 2

题解

需要注意的是最小深度指根节点到最近叶子节点

方式一:BFS

public int minDepth(TreeNode root) {
    if (root == null) return 0;
    if (root.left == null && root.right == null) return 1;
    
    Deque<TreeNode> deque = new LinkedList<>();
    deque.offer(root);
    int result = 1;
    
    while (!deque.isEmpty()) {
        result++;
        int len = deque.size();
        for (int i = 0; i < len; i++) {
            TreeNode node = deque.poll();
            if (node.left != null) {
                if (isLeaf(node.left)) {
                    return result;
                }
                deque.offer(node.left);
            }
            if (node.right != null) {
                if (isLeaf(node.right)) {
                    return result;
                }
                deque.offer(node.right);
            }
        }
    }
    
    return result;
}

boolean isLeaf(TreeNode node) {
    return node.left == null && node.right == null;
}

方式二:DFS

public int minDepth(TreeNode root) {
    if (root == null) return 0;
    if (root.left == null && root.right == null) return 1;

    // 这种写法只处理非空节点,否则不符合叶子节点的题意
    int result = Integer.MAX_VALUE;
    if (root.left != null) {
        result = Math.min(result, minDepth(root.left));
    }
    if (root.right != null) {
        result = Math.min(result, minDepth(root.right));
    }

    return result + 1;
    
    // 这样写就不只是叶子节点了
    // return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}

总结

算法:BFSDFS