您的位置:首页 > 编程语言 > C语言/C++

[Leetcode]Convert Sorted List to Binary Search Tree

2014-11-06 10:45 302 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

第一思路就是先把链表元素取出来,存到数组里,然后用把数组转为平衡BST的方法,结果内存溢出。看来这道题不允许O(n)的空间复杂度。

要用类似数组转为平衡BST的方法,就要不断寻找中间元素。为了减少空间复杂度,只能不断遍历链表,去寻找中间元素。这里用快慢指针可以降低一些求中间元素的时间复杂度。

class Solution{
public:
TreeNode *sortedListToBST(ListNode *head) {
if (NULL == head) return NULL;
return convert(head, NULL);
}
ListNode *searchMid(ListNode *left, ListNode *right){
ListNode *slow = left, *fast = left;
while (fast != right && fast->next != right){
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
TreeNode *convert(ListNode *head, ListNode *end){
if(NULL == head) return NULL;
if (head->next == end || head == end){
TreeNode *newNode = new TreeNode(head->val);
return newNode;
}
ListNode *mid = searchMid(head, end);
TreeNode *newNode = new TreeNode(mid->val);
newNode->left = convert(head,mid);
if(mid->next != end) newNode->right = convert(mid->next,end);
return newNode;
}
};

上边的方法不多说了,比较容易写出来。说实话这个方法中规中矩,时间复杂度比较高。一直想降低复杂度,但是没有想到好方法。在网上看可很多,中递归的方法可以实现O(n)的时间复杂度。
利用中递归,自底向上的用中序构建这棵平衡BST。因为要顺序遍历链表,因此递归中 的节点指针要不断向后移动,所以要使用指针的引用,让指针不断变化。

class Solution{
public:
TreeNode *sortedListToBST(ListNode *head){
int len = calLen(head);
return convert(head, 0, len - 1);
}
int calLen(ListNode *head){
ListNode *tmp = head;
int len = 0;
while (tmp != NULL){
tmp = tmp->next;
len++;
}
return len;
}
TreeNode *convert(ListNode *&node, int left, int right){
if (left > right) return NULL;
int mid = (left + right) >> 1;
TreeNode *leftN = convert(node, left, mid - 1);
TreeNode *root = new TreeNode(node->val);
root->left = leftN;
node = node->next;
root->right = convert(node, mid + 1, right);
return root;
}
};

其实这道题的关键在于把握BST的性质,中序遍历BST,就是升序排列树的元素。那倒过来,顺序遍历升序链表,其实就是按中序自底向上生成平衡BST。

再就是从Run Time来看,两种方法其实差不了多少,都在100多ms。虽然leetcode的运行时间有时不准,但这也一定程度上暴露了递归的弊病----慢.......
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ BST 中序