Wrong answer.. need some explanation


  • 0
    R

    Input: {3,5,8}
    Output: {3,3,5}
    Expected: {5,3,8}

    The code gives a wrong answer, can someone explain why?

    Thank you.

    public class Solution {
        public TreeNode sortedListToBST(ListNode head) {
                int size = countSize(head);
                TreeNode root = Convert(0,size-1,head);
    		  return root;
        }
        public TreeNode Convert(int start, int end, ListNode node){
    		  if(start>end){
    			  return null;
    		  }
    		  int mid = start+(end-start)/2;
    		  TreeNode left = Convert(start, mid-1, node);
    		  TreeNode root = new TreeNode(node.val);
    		  root.left = left;
    		  node = node.next;
    		  root.right = Convert(mid+1, end, node);
    		  return root;
    	  }
    	  public int countSize(ListNode head){
    		  int size = 0;
    		  while(head!=null){
    			  head=head.next;
    			  size++;
    		  }
    		  return size;
    	  }
    }

Log in to reply
 

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