Simple Java solution


  • 1
    J

    The core idea is BFS, when finding a node which its two children is null, the path from the root to this node is the shortest path (minimum depth). Here is the code:

    public class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        
        List<TreeNode> list = new ArrayList<TreeNode>();
        list.add(root);
        
        return levelOrder(list, 0);
    }
    
    private int levelOrder(List<TreeNode> list, int count) {
        count++;
        List<TreeNode> next = new ArrayList<TreeNode>();
        for (TreeNode node : list) {
            if (node.left == null && node.right == null) return count;
            
            if (node.left != null) next.add(node.left);
            if (node.right != null) next.add(node.right);
        }
        return levelOrder(next, count);
    } 
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.