Leetcode Convert Sorted List to Binary Search Tree

OpenSoucre發表於2014-06-23

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

TreeNode *createSearchTree(ListNode *&head, int left , int right){
    if(left > right) return NULL;
    int mid = (left + right)>>1;
    TreeNode *leftChild = createSearchTree(head,left,mid-1);
    TreeNode *parent = new TreeNode(head->val);
    parent->left = leftChild;
    head = head->next;
    parent->right = createSearchTree(head,mid+1,right);
    return parent;
}

TreeNode *sortedListToBST(ListNode *head) {
    if(head == NULL) return NULL;
    int len = 0;
    ListNode *p = head;
    while(p){len++; p = p->next;}
    return createSearchTree(head,0,len-1);    
}

 

相關文章