Sunday, November 30, 2014

Convert Sorted List to Binary Search Tree

from here
class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        int n=getLength(head);
        return sortedListToBST(head, 0, n-1);
    }
    TreeNode* sortedListToBST(ListNode *& list, int start, int end) {
         
          if (start > end) return NULL;
          // same as (start+end)/2, avoids overflow
          int mid = start + (end - start) / 2;
          TreeNode *leftChild = sortedListToBST(list, start, mid-1);
          TreeNode *parent = new TreeNode(list->val);
          parent->left = leftChild;
          list = list->next;
          parent->right = sortedListToBST(list, mid+1, end);
          return parent;
    }
    
    int getLength(ListNode *head)
    {
        int length = 0;
        while (head)
        {
            length++;
            head = head->next;
        }
        return length;
    }
};

No comments:

Post a Comment