/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
TreeNode* sortedArrayToBST(vector<int>& nums,int start,int end)
{
if(start >= end)
{
return NULL;
}
int mid = (start + end)/2;
TreeNode * root = new TreeNode(nums[mid]);
root->left = sortedArrayToBST(nums,start,mid);
root->right = sortedArrayToBST(nums,mid + 1,end);
return root;
}
public:
TreeNode* sortedArrayToBST(vector<int>& nums)
{
return sortedArrayToBST(nums,0,nums.size());
}
};
二叉树的问题多半是要使用递归,提供一个完整的可编译运行的程序,可以调试运行,学习运行过程:
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
TreeNode* sortedArrayToBST(vector<int>& nums,int start,int end)
{
if(start >= end)
{
return NULL;
}
int mid = (start + end)/2;
TreeNode * root = new TreeNode(nums[mid]);
root->left = sortedArrayToBST(nums,start,mid);
root->right = sortedArrayToBST(nums,mid + 1,end);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums)
{
return sortedArrayToBST(nums,0,nums.size());
}
void printBST(TreeNode * root)
{
if(NULL == root)
return;
cout << " " << root->val <<" ";
printBST(root->left);
printBST(root->right);
}
int main()
{
vector <int> nums{-10,-3,0,5,9};
TreeNode *res = sortedArrayToBST(nums);
printBST(res);
return 0;
}