LeetCode:Convert Sorted List to Binary Search Tree
2016-04-14 16:36
465 查看
Convert Sorted List to Binary Search Tree
Total Accepted: 67959 TotalSubmissions: 224265 Difficulty: Medium
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
Hide Tags
Depth-first Search Linked
List
Hide Similar Problems
(M) Convert Sorted Array to Binary Search Tree
code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
return sortedListToBST(head, NULL);
}
TreeNode* sortedListToBST(ListNode* head, ListNode *tail) {
if(head == tail) return NULL;
ListNode *fast = head,*slow = head;
while(fast!=tail && fast->next != tail){ // 找到中间结点
fast = fast->next->next;
slow = slow->next;
}
TreeNode *root = new TreeNode(slow->val);
root->left = sortedListToBST(head, slow);
root->right = sortedListToBST(slow->next, tail);
return root;
}
};
相关文章推荐
- UIAlertView' is deprecated: first deprecated in iOS 9.0 - UIAlertView is deprecated. Use UIAlert
- Springmvc注解启用
- Java内部类:概览(一)
- Java transient关键字
- HandlerThread的用法与自定义HandlerThread(1)
- ubuntu 14.04 + cuda7.0 + opencv2.4.10 + caffe安装记录
- 1234
- epoll + 多线程实现并发网络连接处理
- chrome输入框input黄色背景去除 及 autocomplete失效解决方法
- 给十五个数排序
- maven install时报错Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile
- 用计时器计算1至100的和
- 淘宝天猫网站停止支持IE6、IE7浏览器,你还在用xp吗?
- 质数因子
- chromium源码编译过程中出现的问题及解决方法
- yum与rpm、apt的区别
- zookeeper的坑(二)
- Java并发编程系列之三十二:丢失的信号
- 美女拼图小游戏
- 【学习】Spring 的 AOP :基于Annotation 的“零配置”方式