Leetcode: Convert Sorted Array to Binary Search Tree
来源:互联网 发布:ppsspp源码 编辑:程序博客网 时间:2024/06/05 12:52
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
比较简单。
/** * 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 *sortedArrayToBST(vector<int> &num) { return constructBST(num, 0, num.size() - 1); } TreeNode *constructBST(vector<int> &num, int start, int end) { TreeNode *root = NULL; if (start == end) { root = new TreeNode(num[start]); } else if (start < end) { int mid = (start + end) >> 1; root = new TreeNode(num[mid]); root->left = constructBST(num, start, mid - 1); root->right = constructBST(num, mid + 1, end); } return root; }};
====================第二次=====================
/** * 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 *sortedArrayToBST(vector<int> &num) { return constructBST(num, 0, num.size() - 1); } TreeNode *constructBST(const vector<int> &num, int start, int end) { if (start > end) { return NULL; } int mid = start + (end - start) / 2; TreeNode *root = new TreeNode(num[mid]); root->left = constructBST(num, start, mid - 1); root->right = constructBST(num, mid + 1, end); return root; }};
0 0
- 【LeetCode】Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree
- 【LeetCode】convert-sorted-link-to-binary-search-tree & convert-sorted-array-to-binary-search-tree
- Leetcode - Tree - Convert Sorted Array to Binary Search Tree
- *(leetcode) Convert Sorted Array to Binary Search Tree (tree)
- LeetCode[Tree]: Convert Sorted Array to Binary Search Tree
- LeetCode: Convert Sorted Array to Binary Search Tree
- [LeetCode]Convert Sorted Array to Binary Search Tree
- LeetCode Convert Sorted Array to Binary Search Tree
- [Leetcode] Convert Sorted Array to Binary Search Tree
- leetcode 11: Convert Sorted Array to Binary Search Tree
- Leetcode: Convert Sorted Array to Binary Search Tree
- [LeetCode] Convert Sorted Array to Binary Search Tree
- Leetcode 108 Convert Sorted Array to Binary Search Tree
- Leetcode 108 Convert Sorted Array to Binary Search Tree
- LeetCode Convert Sorted Array to Binary Search Tree
- [LeetCode]Convert Sorted Array to Binary Search Tree
- [Leetcode]Convert Sorted Array to Binary Search Tree
- [leetcode]Convert Sorted Array to Binary Search Tree
- C++ 容器及选用总结
- 重装系统 遇到 windows无法安装到这个磁盘 GPT分区就转化为MBR
- 安装启动bluestacks
- Drawable,Bitmap,byte[]的相互转换
- GCC的内嵌汇编,也就是AT&T汇编语言语法
- Leetcode: Convert Sorted Array to Binary Search Tree
- 可安装多个系统的移动硬盘制作
- hibernate中配置文件的cascade的属性设置
- 我的2013——从早十点到晚十点的日子
- codeforces日记371e
- maven 压缩、合并 js, css
- std::tr1::function 示例(感谢大神)
- 之一:Linux 标准目录结构
- 停用多说插件,谈谈多说的利于弊