[LeetCode] 111. Minimum Depth of Binary Tree ☆(二叉树的最小深度)

[Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度 (最小有3种解法)

描述

解析

递归深度优先搜索

当求最大深度时,我们只要在左右子树中取较大的就行了。

然而最小深度时,如果左右子树中有一个为空会返回0,这时我们是不能算做有效深度的。

所以分成了三种情况,左子树为空,右子树为空,左右子树都不为空。当然,如果左右子树都为空的话,就会返回1。

广度优先搜索(类似层序遍历的思想)

递归解法本质是深度优先搜索,但因为我们是求最小深度,并不一定要遍历完全部节点。如果我们用广度优先搜索,是可以在遇到第一个叶子节点时就终止并返回当前深度的。

代码

递归深度优先搜索

/**
 * 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;
        }
        int depth = 0;
        if(root.left != null && root.right != null){
            int left = minDepth(root.left);
            int right = minDepth(root.right);
            depth = Math.min(left, right);
        } else if (root.left != null){
            depth = minDepth(root.left);
        } else if (root.right != null){
            depth = minDepth(root.right);
        }
        return depth + 1;
    }
}

广度优先搜索(类似层序遍历的思想)

public class Solution {
    public int minDepth(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if(root!=null) queue.offer(root);
        int depth = 0;
        while(!queue.isEmpty()){
            int size = queue.size();
            depth++;
            for(int i = 0; i < size; i++){
                TreeNode curr = queue.poll();
                if(curr.left == null && curr.right == null){
                    return depth;
                }
                if(curr.left != null) queue.offer(curr.left);
                if(curr.right != null) queue.offer(curr.right);
            }
        }
        return depth;
    }
}
原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/10614987.html