您的位置:首页 > 其它

把排序数组转化为高度最小的二叉树

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: