Convert Sorted Array to Binary Search Tree
2015-07-31 10:38
417 查看
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Analyse: Using binary search to divide the sorted array into two parts, then recursively do the same process for the two parts.
Runtime: 16ms.
Additional: IT'S THE FIRST TIME I COME UP WITH A SOLUTION WITHOUT REFERENCE. CONG!!
Analyse: Using binary search to divide the sorted array into two parts, then recursively do the same process for the two parts.
Runtime: 16ms.
Additional: IT'S THE FIRST TIME I COME UP WITH A SOLUTION WITHOUT REFERENCE. CONG!!
/** * 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* sortedArrayToBST(vector<int>& nums) { if(nums.size() == 0) return NULL; return convert(nums, 0, nums.size() - 1); } TreeNode* convert(vector<int>& nums, int low, int high){ if(low > high) return NULL; int mid = (low + high) / 2; TreeNode* root = new TreeNode(nums[mid]); if(low == high) return root; root->left = convert(nums, low, mid - 1); root->right = convert(nums, mid + 1, high); return root; } };
相关文章推荐
- HDU 5328 Problem Killer(水题)
- Crontab 让linux定时执行shell脚本
- hadoop入门--hadoop
- ubuntu 环境下编译 hadoop 2.6.0的简单方法
- linux部署jdk和tomcat
- 模仿仿微信发表朋友圈图片多选实现
- linux常用命令
- MyKTV项目总结
- [转]ORACLE 审计功能
- enmo_day_07
- enmo_day_06
- 性能各个指标分析
- (转载)半波/全波精密整流电路概述
- 数据库连接池druid wallfilter配置
- iOS实现二维码的扫描功能
- android.content.res.Resources$NotFoundException: String resource ID #0x1
- 你会提问吗?谈如何向高手请教问题
- 待解决问题
- EclipseLink JPA 2.1
- java 中四大加密基本算法解析