Easy understand way using BFS(using java)


  • 0
    S

    public class Solution {

    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        
        Queue<TreeNode> queue = new LinkedList();
        queue.offer(root);
        int depth = 0;
        
        while (!queue.isEmpty()) {
            depth++; // BFS enter the next depth
            int size = queue.size();          
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null) return depth; // return if found a leaf
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
        }
        return depth;
    }
    

    }


Log in to reply
 

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