您的位置:首页 > 其它

77:Convert Sorted List to Binary Search Tree

2017-03-08 23:10 113 查看
题目:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced

BST.

解析1:可以采用和转换有序数组到二分查找树这一问题相同的解法,先构造根节点,然后再构造其左右树的结点,该方法被称之为自顶向下法,但是需要注意的是单链表不能随机访问,代码如下:

// 自顶向下,时间复杂度 O(nlogn),空间复杂度 O(logn)
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
return sortedListToBSL(head, listLength(head));
}

TreeNode* sortedListToBST(ListNode* head, int len) {
if (len == 0) return nullptr;
if (len == 1) return new TreeNode(head -> val);

TreeNode* root = new TreeNode(nth_node(head, len / 2 + 1) -> val);
root -> left = sortedListToBST(head, len / 2);
root -> right = sortedListToBST(nth_node(head, len / 2 + 2), (len - 1) / 2);
return root;
}

int listLength(ListNode* node) {
int n = 0;
while (node) node = node -> next, ++n;
return n;
}

ListNode* nth_node(ListNode* node, int n) {
while (--n)
node = node -> next;
return node;
}
};


解析2:也可以采用自底向上法,即先构造左子树,然后再构造根节点,最后构造右子树,该方法时间复杂度为 O(n),代码如下:

// 自底向上,时间复杂度 O(n),空间复杂度 O(logn)
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
int len = 0;
ListNode* p = head;
while (p) {
len++;
p = p -> next;
}
// [0, len)
return sortedListToBST(head, 0, len);
}
private:
// [start, end)
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);
TreeNode* parent = new TreeNode(list -> val);
parent -> left = leftChild;
list = list -> next;
parent -> right = sortedListToBST(list, mid + 1, end);
return parent;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: