Easy to understand solution

  • 0

    The idea is first loop through the ListNode and store each node's value into an arraylist. Then the rest of the step is same as previous question.

      public TreeNode sortedListToBST(ListNode head) {
          if( head == null ) return null;
          List<Integer> l = new ArrayList<>();
          while( head != null ){
              head = head.next;
          TreeNode root = helper(l,0,l.size()-1);
          return root;
      private TreeNode helper(List<Integer> l, int lo, int hi ){
          if( lo>hi ) return null;
          int mid = (lo+hi)/2;
          TreeNode root = new TreeNode(l.get(mid));
          root.left = helper(l,lo,mid-1);
          root.right = helper(l,mid+1, hi);
          return root;

Log in to reply

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