- 构造的关键点就是找到树的根结点
- 每个子树也是找其的根结点
- 注意如果构造一个线性二叉树也是搜索树,但不符合题意
cpp
#include <iostream>
#include <vector>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(): val(0), left(nullptr), right(nullptr) {}
TreeNode(int v): val(v), left(nullptr), right(nullptr) {}
TreeNode(int v, TreeNode* l, TreeNode* r): val(v), left(l), right(r) {}
};
class Solution {
private:
TreeNode* traversal(std::vector<int>& nums, int left, int right) {
if (left > right)
return nullptr;
int mid = (left + right) / 2;
TreeNode* root = new TreeNode(nums.at(mid));
root->left = traversal(nums, left, mid - 1);
root->right = traversal(nums, mid + 1, right);
return root;
}
public:
TreeNode* sortedArrayToBST(std::vector<int>& nums) {
return traversal(nums, 0, nums.size() - 1);
}
};
int main()
{
Solution s;
return 0;
}