LeetCode Convert Sorted List to Binary Search Tree
来源:互联网 发布:农村淘宝怎么取消绑定 编辑:程序博客网 时间:2024/06/06 03:15
这题刚开始的做法是把链表中的元素放到数组,然后按照上一题的做法,结果出现内存不够用而通不过,再想想,和上题相似,对链表递归操作,每次找到中间位置就行了,只不过时间复杂度增加了点,但对于链表这不可避免的。如下:
TreeNode *resusiveListToBST(ListNode *head,int num) {if(head==NULL||num<=0)return NULL;TreeNode *tp;if (num==1){tp = new TreeNode(head->val);return tp;}int half = num/2;ListNode *lp=head;while(half){half--;lp = lp->next;}tp = new TreeNode(lp->val);tp->left = resusiveListToBST(head,num/2);tp->right = resusiveListToBST(lp->next,num - num/2 - 1);return tp;}TreeNode *sortedListToBST(ListNode *head) {if(head==NULL)return NULL;int lennum=0;ListNode *lp=head;while(lp){lennum++;lp = lp->next;}return resusiveListToBST(head,lennum);}
0 0
- 【LeetCode】Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree
- LeetCode[Tree]: Convert Sorted List to Binary Search Tree
- [leetcode][list][dfs] Convert Sorted List to Binary Search Tree
- LeetCode: Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- LeetCode : Convert Sorted List to Binary Search Tree
- [Leetcode] Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Balanced Binary Search Tree
- [LeetCode] Convert Sorted List to Binary Search Tree
- leetcode 66: Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode:Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- [Leetcode]Convert Sorted List to Binary Search Tree
- [leetcode]Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Binary Search Tree
- 从键盘输入一系列字符串。写入到某磁盘文件中
- 黑马程序员05_正则表达式
- 【转】Orion - oracle提供的测试io性能的工具
- EF中关于存储过程的操作
- OpenCV学习笔记-自适应阈值化
- LeetCode Convert Sorted List to Binary Search Tree
- 2014ACM集训13级PK赛3-Yet Another Story of Rock-paper-scissors
- Android笔记- fragment 基本了解
- 建DNS之缓存,解Ubuntu之网慢
- Windows下用C++关闭某个窗口的简单方法
- WinCE 项目记录
- 蛇形填数
- android Animations 动画效果(二)
- POJ 2479 Maximum sum[DP]