Convert Sorted List to Binary Search Tree

LeetCode #109


Description:

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

Example:

Idea:

这题与上一题类似,但是单链表不能随机访问,而自顶向下的二分法必须需要 RandomAccessIterator,因此前面的方法不适用本题。 存在一种自底向上 (bottom-up) 的方法.

构建过程相当于inorder。

Time: O(n), Space:(logn)

Code:

class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        int len=0;
        ListNode* p=head;
        while(p!=NULL){
            len++;
            p=p->next;
        }

        return sortedListToBST(head, 0, len-1);
    }

    // [first, last] is left and right inclusive
    // ListNode should be reference, it will be modified and move one step 
    TreeNode* sortedListToBST(ListNode*& head, int first, int last){
        if(first>last) return NULL;

        int mid=first+(last-first)/2;

        TreeNode* left=sortedListToBST(head, first, mid-1); // recursively Construct left tree first
        TreeNode* root=new TreeNode(head->val);
        root->left=left;
        head=head->next;
        root->right=sortedListToBST(head, mid+1, last);

        return root;
    }
};

results matching ""

    No results matching ""