leetcode - Convert Sorted List to Binary Search Tree
2015-08-22 09:58
375 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) :val(x), left(NULL), right(NULL) {} }; class Solution { public: TreeNode *sortedListToBST(ListNode *head) { int n = 0; ListNode *p = head; while(p != NULL) { p = p->next; n++; } return ListToBST(head,0,n-1); } private: TreeNode *ListToBST(ListNode *&head,int start, int end) { if(start > end) return NULL; int mid = (start + end) / 2; TreeNode *left = ListToBST(head,start,mid - 1); TreeNode *node = new TreeNode(head->val); node->left = left; head = head->next; node->right = ListToBST(head,mid + 1,end); return node; } };
相关文章推荐
- iOS笔记 (2)
- windows编程之进程通信:内存共享
- HDU-5146_Sequence
- vector里插入类的对象
- 【LeetCode】(242)Valid Anagram(Easy)
- Aborting commit: 'XXXXXXXX'remains in conflict错误
- hdu4310 贪心
- 报错:tr was not declared in this scope
- Redhat安装mysql及 导出数据库
- mysql 外键的记载
- QT 主窗口和非模态对话框切换 以及消息通信
- Android studio的下载安装配置详解 (上)
- 行为表
- 控制器的生命周期
- myeclipse2014安装反编译插件
- RedHat命令行和图形界面切换
- iOS 网络开发NSURLConnection——使用block回调方法发送异步请求
- Swift面向对象介绍(一)
- 神经网络ANN——SPSS实现
- cmd下使用命令制作U盘启动盘