Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Solution:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
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.size()!=0){
            depth++;
            Queue<TreeNode> tmp = new LinkedList<>();
            while(queue.size()!=0){
                TreeNode tn = queue.poll();
                if(tn.left==null && tn.right==null) return depth;
                if(tn.left!=null) tmp.offer(tn.left);
                if(tn.right!=null) tmp.offer(tn.right);
            }
            queue = tmp;
        }
        return -1;
    }
}
comments powered by Disqus