您的位置:首页 > 其它

Convert Sorted List to Binary Search Tree

2013-05-09 17:34 363 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

思路:和Convert Sorted Array to BST不同的地方在于,对于list不能直接取到第n个结点,如果采用同样的方法,必然要很高的复杂度,能不能用同样的O(n)解决呢?

As usual, the best solution requires you to think from another perspective. In other words, we no longer create nodes in the tree using the top-down approach. We create nodes bottom-up, and assign them to its parents. The bottom-up approach enables us to
access the list in its order while creating nodes.

Isn't the bottom-up approach neat? Each time you are stucked with the top-down approach, give bottom-up a try. Although bottom-up approach is not the most natural way we think, it is extremely helpful in some cases. However, you should prefer top-down instead
of bottom-up in general, since the latter is more difficult to verify in correctness.

Below is the code for converting a singly linked list to a balanced BST. Please note that the algorithm requires the list's length to be passed in as the function's parameters. The list's length could be found in O(N) time by traversing the
entire list's once. The recursive calls traverse the list and create tree's nodes by the list's order, which also takes
O(N) time. Therefore, the overall run time complexity is still
O(N).

代码如下:

class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len = 0;
ListNode* p = head;
while(p != NULL)
{
len++;
p = p->next;
}

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

TreeNode *construct(ListNode* &head,int start,int end)
{
if(start > end) return NULL;

int mid = (start + end+1)/2;
TreeNode* left = construct(head,start,mid-1);
TreeNode* root= new TreeNode(head->val);
root->left = left;
head = head->next;
root->right = construct(head,mid+1,end);
return root;
}

};


156 milli secs
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: