My BFS solution


  • 0
    S

    Add null to split nodes of different level.

    public class Solution {
        public int minDepth(TreeNode root) {
            if(root == null)    return 0;
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            queue.add(null);
            int count = 1;
            while(queue.size()!= 0){
                TreeNode node = queue.poll();
                if(node == null && queue.size()!= 0){    
                    count++;
                    queue.add(null);
                }
                else{
                    if(node.left == null && node.right == null)
                        break;
                    if(node.left != null)
                        queue.add(node.left);
                    if(node.right != null)
                        queue.add(node.right);
                }
            }
            return count;
        }
    }

Log in to reply
 

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