题目.jpg
题目.jpg
题目.jpg
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <unordered_map>
#include <utility>
#include <algorithm>
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) {}
};
class Solution {
public:
// 解题思路:使用有序数组的中间位置作为区间分割点,然后递归左区间和右区间
// 1.确定递归函数入参及返回值
TreeNode* Traversal(vector<int>& nums, int left, int right) {
// 2.确定递归终止条件
if(left > right) return nullptr;
// 3.确定单层递归逻辑
int mid = left + ((right - left) / 2); // 当left和right很大时防止越界,所以求中间位置时这样写
TreeNode* node = new TreeNode(nums[mid]);
node->left = Traversal(nums, left, mid - 1); // 左区间[left, mid - 1]
node->right = Traversal(nums, mid + 1, right); // 右区间[mid + 1, right]
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root = Traversal(nums, 0, nums.size() - 1);
return root;
}
};
网友评论