Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
O(n) solution
BinaryTree* sortedListToBST(ListNode *& list, int start, int end) {
if (start > end) return NULL;
// same as (start+end)/2, avoids overflow
int mid = start + (end - start) / 2;
BinaryTree *leftChild = sortedListToBST(list, start, mid-1);
BinaryTree *parent = new BinaryTree(list->data);
parent->left = leftChild;
list = list->next;
parent->right = sortedListToBST(list, mid+1, end);
return parent;
}
BinaryTree* sortedListToBST(ListNode *head, int n) {
return sortedListToBST(head, 0, n-1);
}
本文介绍了一种O(n)复杂度的算法,用于将已排序的链表转换为高度平衡的二叉搜索树。通过递归的方式实现,确保树的高度最小化,提高查找效率。
412

被折叠的 条评论
为什么被折叠?



