LeetCode:Convert Sorted List to Binary Search Tree
2014-03-23 17:20
531 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Solution:
这种bottom-up 方法很巧妙
Time complexity:O(N)
http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html
Solution:
/** * 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) {} * }; */ class Solution { public: TreeNode *sortedListToBST(ListNode *head) { int len = 0; ListNode *p = head; while(p){ len++; p = p->next; } return sortedListToBST(head,0,len-1); } private: TreeNode *sortedListToBST(ListNode*& head,int l,int h){ if(l > h) return NULL; int mid = l + (h-l)/2; TreeNode *lChiled = sortedListToBST(head,l,mid-1); TreeNode *p = new TreeNode(head->val); p->left = lChiled; head = head->next; p->right = sortedListToBST(head,mid+1,h); return p; } };
这种bottom-up 方法很巧妙
Time complexity:O(N)
http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html
相关文章推荐
- 第三周作业
- 利用STM32的Systick中断实现按键消抖
- linux下使用mysql的小问题
- 安装VirtualBox
- 获取输入框中选中文本相对于页面的偏移
- 正则表达式基础
- java基础_10_泛型
- TWaver HTML5学习笔记 —— 动态设置网元样式
- 将Eclipse项目自动部署到Tomcat的webapps目录下
- android手势操作滑动效果触摸屏事件处理
- oracle vm virtualbox按照Ubuntu
- C#之 基本.NET 框架类
- course 4 分治
- 面试笔记2
- C语言深度解剖读书笔记
- C语言枚举类型
- Cocos2d-x学习笔记(三) 内存管理
- CentOS–root密码忘记的解决办法
- 网络编程
- 命令提示符在哪里