从有序链表创造平衡二叉搜索树 [英] Create Balanced Binary Search Tree from Sorted linked list
本文介绍了从有序链表创造平衡二叉搜索树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是从排序单链表建立一个平衡的二叉搜索树的最佳方法是什么?
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);
}
这篇关于从有序链表创造平衡二叉搜索树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文