将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定有序数组: [-10,-3,0,5,9],
一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
0
/ \
-3 9
/ /
-10 5
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* buildAVL(int left, int right, vector<int> &nums)
{
if(left > right)
return NULL;
else if(left == right){
TreeNode* root = new TreeNode(nums[left]);
return root;
}
else{
TreeNode* root;
int mid = (left + right) / 2;
root = new TreeNode(nums[mid]);
root->left = buildAVL(left, mid - 1, nums);
root->right = buildAVL(mid + 1, right, nums);
return root;
}
}
TreeNode *sortedArrayToBST(vector<int> &nums)
{
TreeNode *root = NULL;
int size = nums.size();
if (size == 0)
return root;
root = buildAVL(0, size - 1, nums);
return root;
}
void print(TreeNode *r)
{
if (!r)
return;
print(r->left);
cout << r->val << " ";
print(r->right);
}
int main()
{
int a[5] = {-10,-3,0,5,9};
vector<int>nums(a,a+5);
TreeNode* root = sortedArrayToBST(nums);
print(root);
return 0;
}
简化代码后:
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* buildAVL(int left, int right, vector<int> &nums)
{
if(left > right)
return NULL;
int mid = (left + right) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = buildAVL(left, mid - 1, nums);
root->right = buildAVL(mid + 1, right, nums);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &nums)
{
return buildAVL(0, nums.size() - 1, nums);
}
void print(TreeNode *r)
{
if (!r)
return;
print(r->left);
cout << r->val << " ";
print(r->right);
}
int main()
{
int a[5] = {-10,-3,0,5,9};
vector<int>nums(a,a+5);
TreeNode* root = sortedArrayToBST(nums);
print(root);
return 0;
}