什么是从排序单链表建立一个平衡的二叉搜索树的最佳方法是什么?
What's the best way to create a balanced binary search tree from a sorted singly linked list?
如何创建节点自下而上的?
How about creating nodes bottom-up?
此解决方案的时间复杂度为O(N)。详细解释在我的博客文章:
This solution's time complexity is O(N). Detailed explanation in my blog post:
的http:// www.leet code.com / 2010/11 /转换排序列表到平衡binary.html
二遍历链表是我们所需要的。优先遍历获得列表的长度(其然后被传递作为参数n到函数),然后创建根据列表的顺序节点
Two traversal of the linked list is all we need. First traversal to get the length of the list (which is then passed in as the parameter n into the function), then create nodes by the list's order.
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);
}