Very neat iterative solution in java


  • 0
    C
    public class Solution {
        public int minDepth(TreeNode root) {
            if(root == null) return 0;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);
            int depth = 1, size = 1;
            while(!queue.isEmpty()){
                TreeNode node = queue.poll();
                if(node.right == null && node.left == null) return depth;
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
                if(--size == 0){
                    depth++;
                    size = queue.size();
                }
            }
            return depth;
        }
    }

Log in to reply
 

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