您的位置:首页 > 其它

Leetcode:Convert Sorted List to Binary Search Tree

2015-08-11 10:01 495 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced

BST.

// LeetCode, Convert Sorted List to Binary Search Tree
// bottom-up,时间复杂度O(n),空间复杂度O(logn)
class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
int len = 0;
ListNode *p = head;
while (p) {
len++;
p = p->next;
}
return sortedListToBST(head, 0, len - 1);
}
private:
TreeNode* sortedListToBST(ListNode*& list, int start, int end) {
if (start > end) return nullptr;
int mid = start + (end - start) / 2;
TreeNode *leftChild = sortedListToBST(list, start, mid - 1);
TreeNode *parent = new TreeNode(list->val);
parent->left = leftChild;
list = list->next;
parent->right = sortedListToBST(list, mid + 1, end);
return parent;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: