[Thoughts]
It is similar with “Convert Sorted Array to Binary Search Tree“. But the difference here is we have no way to random access item in O(1).
If we build BST from array, we can build it from top to bottom, like
1. choose the middle one as root,
2. build left sub BST
3. build right sub BST
4. do this recursively.
But for linked list, we can’t do that because Top-To-Bottom are heavily relied on the index operation.
There is a smart solution to provide an Bottom-TO-Top as an alternative way, http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html
With this, we can insert nodes following the list’s order. So, we no longer need to find the middle element, as we are able to traverse the list while inserting nodes to the tree.
[Code]
1: TreeNode *sortedListToBST(ListNode *head) {
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: int len =0;
5: ListNode *p = head;
6: while(p)
7: {
8: len++;
9: p = p->next;
10: }
11: return BuildBST(head, 0, len-1);
12: }
13: TreeNode* BuildBST(ListNode*& list, int start, int end)
14: {
15: if (start > end) return NULL;
16: int mid = (start+end)/2; //if use start + (end - start) >> 1, test case will break, strange!
17: TreeNode *leftChild = BuildBST(list, start, mid-1);
18: TreeNode *parent = new TreeNode(list->val);
19: parent->left = leftChild;
20: list = list->next;
21: parent->right = BuildBST(list, mid+1, end);
22: return parent;
23: }
将排序链表转换为高度平衡二叉搜索树
本文详细介绍了如何将已排序的链表转换为高度平衡的二叉搜索树,通过构建中序遍历的方式实现,提供了一种不同于数组转换的方法,旨在优化时间和空间复杂度。
409

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



