My java 1ms use BFS


  • 1
    /**
     * 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> comeIn=new LinkedList<TreeNode>();
            int res=0;
            comeIn.offer(root);
            while(!comeIn.isEmpty()){
                int size=comeIn.size();
                res++;
                for(int i = 0;i < size; ++ i){
                    TreeNode tmp=comeIn.poll();
                    if(tmp.left == null && tmp.right == null)
                        return res;
                    if(tmp.left != null)
                        comeIn.offer(tmp.left);
                    if(tmp.right != null)
                        comeIn.offer(tmp.right);    
                }
            }
            return 520;
        }
    }

  • 0
    Z

    is it a magic ? what return 520 can get correct result ?


  • 0
    H

    It could be any other integer. It only serves for grammatical purpose: without it the compiler may think there could be no return value.


Log in to reply
 

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