[LeetCode] Convert Sorted List to Binary Search Tree, Solution

将排序链表转换为高度平衡二叉搜索树
本文详细介绍了如何将已排序的链表转换为高度平衡的二叉搜索树,通过构建中序遍历的方式实现,提供了一种不同于数组转换的方法,旨在优化时间和空间复杂度。

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

» Solve this problem

[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: }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值