Java Solution recursive & non recursive


  • 0
    J

    Recursive

      public int minDepth(TreeNode root) {
            if(root == null) return 0;
            int left = minDepth(root.left);
            int right = minDepth(root.right);
            return (left == 0 || right == 0)? left + right + 1: Math.min(left,right) +1;
        }
    

    Non Recursive

     public int minDepth(TreeNode root) {
            if(root == null) return 0;
             int depth = 1;   // level
             int count = 1;   // nodes in each level
             Queue<TreeNode> queue = new LinkedList<>();
             queue.offer(root);
             while(!queue.isEmpty()){
                 TreeNode current = queue.poll();
                 count -- ;
                 if(current.left != null){
                     queue.offer(current.left);
                 }
                 if(current.right != null){
                     queue.offer(current.right);
                 }
                 if(current.right == null && current.left == null){
                     break;
                 }
                 if(count == 0){
                     count = queue.size();
                     depth ++;
                 }
             }
             return depth;
        }
    

Log in to reply
 

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