Leetcode 109. Convert Sorted List to Binary Search Tree
来源:互联网 发布:兰州ps软件班 编辑:程序博客网 时间:2024/05/17 08:28
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
s思路:
1. Leetcode 108. Convert Sorted Array to Binary Search Tree的变形。这回不用vector,改用list。两者有什么区别吗?链表要访问中间某个节点需要从头一个一个移动到所要找的位置,即:查询的复杂度o(n),而vector的查询可以一步到位o(1)。因此,不能通过计算中点的方法来做,试试用iterative,从左往右遍历list。
2. 参考了https://discuss.leetcode.com/topic/3286/share-my-code-with-o-n-time-and-o-1-space 对list用iterative,对BST还用recursive. 按照以上链接的说法:对bst用in-order遍历,由于list就是inorder的顺序,那么bst inorder就和list刚好match。具体说:先知道list长度,然后按照inorder遍历的方式构造左子树,中间节点,右子树。
3. 由于每个节点只访问一次,故o(n)。这道题,技巧性比较强。但是把list和tree放在一起,还是不错!
class Solution {//private: //ListNode* head;//注意:用reference的效果和用private变量的作用一样 //需要在所有recursive调用过程中改变一个变量,即这个变量是全局变量!public: int number(ListNode* head){ int count=0; while(head){ count++; head=head->next; } return count; } TreeNode* helper(int n,ListNode* &head){//bug:ListNode& *head,复习一下,ListNode*是一种数据类型,所以应该用ListNode* &表示是(ListNode*)的reference! if(n==0) return NULL; TreeNode* cur=new TreeNode(0);//先建一个空树, cur->left=helper(n/2,head);//先访问左边, cur->val=head->val;//再访问中间,赋值, head=head->next;//赋值后,移动list cur->right=helper(n-n/2-1,head);//最后访问右边 return cur; } TreeNode* sortedListToBST(ListNode* head) { //this->head=head; return helper(number(head),head); }};
0 0
- LeetCode 109. Convert Sorted List to Binary Search Tree
- [LeetCode]109.Convert Sorted List to Binary Search Tree
- 109.Convert Sorted List to Binary Search Tree Leetcode Python
- [Leetcode] 109. Convert Sorted List to Binary Search Tree
- LeetCode --- 109. Convert Sorted List to Binary Search Tree
- [leetcode] 109.Convert Sorted List to Binary Search Tree
- 109. Convert Sorted List to Binary Search Tree LeetCode
- [leetcode] 109. Convert Sorted List to Binary Search Tree
- Leetcode 109. Convert Sorted List to Binary Search Tree
- [LeetCode]109. Convert Sorted List to Binary Search Tree
- LeetCode *** 109. Convert Sorted List to Binary Search Tree
- LeetCode 109. Convert Sorted List to Binary Search Tree
- LeetCode - 109. Convert Sorted List to Binary Search Tree
- Leetcode 109. Convert Sorted List to Binary Search Tree
- [leetcode] 109. Convert Sorted List to Binary Search Tree
- [LeetCode] 109. Convert Sorted List to Binary Search Tree
- Leetcode-109. Convert Sorted List to Binary Search Tree
- 【leetcode】109. Convert Sorted List to Binary Search Tree
- 10.2 信号处理
- VTK修炼之道48:图形基本操作进阶_符号化操作与模型区率计算
- Redis使用详细教程
- windows下安装lxml
- jquery入门
- Leetcode 109. Convert Sorted List to Binary Search Tree
- python2.7 or not 运算符规则
- PART IV 程序设计层 Chapter 8 高级程序设计语言
- mac 配置maven环境变量
- android关于ViewGroup的一些事一些情
- [SinGuLaRiTy-1001] Calculation Of The Shortest Path 最短路算法集锦
- Problem D. Soldiers Google APAC 2017 University Test Round C
- codevs天梯 矩阵取数游戏(昨天太忙没放题上来。。。)高精度+dp
- 《剑指offer》--- 链表中的倒数第k个结点 和 反转链表