您的位置:首页 > 其它

LeetCode - Convert Sorted List to Binary Search Tree

2014-02-13 01:00 309 查看
Convert Sorted List to Binary Search Tree

2014.2.13 00:46

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

Solution:

  You may already have solved the problem Convert Sorted Array to Binary Search Tree, which can be done in O(n) time.

  Since linked list is sequential data structure, accessing a node requires O(n) time. The solution is similar for this problem, but time complexity is O(n * log(n)), instead of O(n). Space complexity remains the same O(n).

  T(n) = 2 * T(n / 2) + O(n) => T(n) = O(n * log(n))

  Another more efficient solution is to convert the linked list to array using an extra vector, and Convert Sorted Array to Binary Search Tree. At least both steps run in O(n) time, it's more efficient after all. Space complexity remains in O(n) scale, but the constant scalar becomes larger.

Accepted code:

// 1CE, 1AC, excellent.
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
if (head == nullptr) {
return nullptr;
}
int n = 0;
ListNode *ptr = head;
while (ptr !=  nullptr) {
ptr = ptr->next;
++n;
}

if (n == 1) {
return new TreeNode(head->val);
}

int nl, nr;
int i;
ListNode *head1, *root, *head2;

nr = (n - 1) / 2;
nl = n - 1 - nr;
// nl must be positive
// nr could be 0
ptr = head;
for (i = 0; i < nl - 1; ++i) {
ptr = ptr->next;
}
head1 = head;
root = ptr->next;
ptr->next = nullptr;
head2 = root->next;
root->next = nullptr;

TreeNode *tree_root = nullptr;

tree_root = new TreeNode(root->val);
tree_root->left = sortedListToBST(head1);
tree_root->right = sortedListToBST(head2);

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