[leetcode]Convert Sorted Array to Binary Search Tree
2015-11-02 23:09
375 查看
Convert Sorted Array to Binary Search Tree My Submissions Question
Total Accepted: 57734 Total Submissions: 165322 Difficulty: Medium
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
递归解决,一遍过的感觉不要太爽啊 哈哈~
暂时忽略函数命名。。。不要让想函数名扰乱我的思路:)
Total Accepted: 57734 Total Submissions: 165322 Difficulty: Medium
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Subscribe to see which companies asked this question
/** * 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) { int len = nums.size(); if(!len) return nullptr; int l = 0; int r = len - 1; int mid = l + (r - l) / 2; TreeNode* root = new TreeNode(nums[mid]); root->left = func(nums,l,mid - 1); root->right = func(nums,mid + 1,r); return root; } TreeNode* func(const vector<int>& nums,int l,int r){ if(l > r) return nullptr; int mid = l + (r - l) / 2; TreeNode* root = new TreeNode(nums[mid]); root->left = func(nums,l,mid - 1); root->right = func(nums,mid + 1,r); return root; } };
递归解决,一遍过的感觉不要太爽啊 哈哈~
暂时忽略函数命名。。。不要让想函数名扰乱我的思路:)
相关文章推荐
- JavaScript API 设计原则
- mysql远程设置
- Jeecms去除Eclipse开发环境中的项目名
- 尺取法 Codeforces591C Median Smoothing
- Python 遍历二叉树
- smab的配置
- AngularJS控制器controller之间通信
- Objective-C函数指针
- IOS项目笔记-1
- 让网店在百度有个身份----注册域名绑定网店不完全教程
- 阿健的iOS开发Demo(加法计算器、图片浏览(动画))
- CentOS备忘
- OC02 实例变量可见度和方法-1
- 特殊容器:符号表-为查找而生的结构
- VMware 12安装虚拟机Mac OS X 10.10使用小技巧(虚拟机Mac OS X 10.10时间设置,虚拟机Mac OS X 10.10通过代理上网,Mac OS X 10.10虚拟机优化,VMware虚拟机相互复制)
- NOI题库2.5 6264 走出迷宫
- 【随机过程】随机过程之更新过程(2)
- 【15.10.30考试】考试分析
- Android_仿支付宝账单列表(头部停留及分页数据加载)
- COGS41. [NOIP2003] 麦森数