把排序数组转化为高度最小的二叉树
2017-06-20 20:24
302 查看
把排序数组转化为高度最小的二叉树
思路:直接采用中间值来作为二叉树的根节点;将原数组分成左右均等或者相差一个数的两个新数组;然后递归的对这两个新数组进行相同的处理,这样对于每一个根节点,其左右子树的高度相差绝对值不会超过1,也就是满足了二叉平衡树的要求了。struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) :val(x) {} }; class Solution { public: TreeNode* sortedArrToBST(vector < int>& array) { if (array.empty())return nullptr; return sortedArrToBSTcore(array, 0, array.size() - 1); } TreeNode* sortedArrToBSTcore(vector < int>& array, int low, int high) { if (low <= high) { int mid = (low + high) / 2; TreeNode* pRoot = new TreeNode(array[mid]); pRoot->left= sortedArrToBSTcore(array, low, mid - 1); pRoot->right= sortedArrToBSTcore(array, mid+1, high); return pRoot; } return nullptr; } };
有1,2,3一直到n的无序数组,排序
原始数组:
a = [ 10, 6,9, 5,2, 8,4,7,1,3 ]
如果把它们从小到大排序且应该是
b = [1,2,3,4,5,6,7,8,9,10 ]
也就是说: 如果我们观察 a --> b 的对映关系是:
a[ i ] 在 b 中的位置是 b[ a[i] - 1]
void sortArrOf1toN(vector<int>& vec) { vector<int> res(vec.size()); for (auto m : vec) res[m-1] = m; vec = res; }
相关文章推荐
- 把排序数组转化为高度最小的二叉搜索树
- 给定一个有序数组(递增),写程序构建一棵具有最小高度的二叉树。
- 题目:把排序数组转换为高度最小的二叉搜索树
- 把排序数组转换为高度最小的二叉搜索树
- lintcode把排序数组转换为高度最小的二叉搜索树
- LintCode 把排序数组转换为高度最小的二叉搜索树
- 把顺序数组转为高度最小的二叉树(算法)
- lintCode(177)——把排序数组转换为高度最小的二叉搜索树
- lintcode,把排序数组转换为高度最小的二叉搜索树
- LintCode:把排序数组转换为高度最小的二叉搜索树
- 把排序数组转换为高度最小的二叉搜索树
- 给定一个有序数组(递增),构建一棵具有最小高度的二叉树
- 根据一个已排序数组构造一棵二叉树,要求树的高度最少
- 把排序数组转换为高度最小度二叉搜索树
- Chapter 4 | Trees and Graphs--有序数组构建最小高度的二叉树
- 给定一个有序数组(递增),构建一棵具有最小高度的二叉树
- 把排序数组转换为高度最小的二叉搜索树(LintCode)
- 把排序数组转换为高度最小的二叉搜索树convert-sorted-array-to-binary-search-tree-with-minimal-height
- 把排序数组转换为高度最小的二叉搜索树-LintCode
- LintCode | 177. 把排序数组转换为高度最小的二叉搜索树