class Solution {
// 1. 找到最大值
// 2. 对左区间、右区间递归调用
public:
// 左闭右闭
int findMaxValueIndex(vector<int>& nums, int left, int right) {
int index = -1;
int max_value = INT_MIN;
for (int i = left; i <= right; i++) {
if (nums[i] > max_value) {
index = i;
max_value = nums[i];
}
}
return index;
}
TreeNode* travarsel(vector<int>& nums, int left, int right) {
// 确定终止条件
if (left == right) {
TreeNode* new_node = new TreeNode(nums[left]);
return new_node;
}
// 单层递归逻辑
int root_value_index = findMaxValueIndex(nums, left, right);
TreeNode* root = new TreeNode(nums[root_value_index]);
if (root_value_index > left) {
root->left = travarsel(nums, left, root_value_index - 1);
}
if (root_value_index < right) {
root->right = travarsel(nums, root_value_index + 1, right);
}
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if (0 == nums.size()) return nullptr;
return travarsel(nums, 0, nums.size() - 1);
}
};
class Solution {
public:
TreeNode* traversal (TreeNode* root1, TreeNode* root2) {
// 确定终止条件
if (root1 == nullptr && root2 == nullptr) return nullptr;
if (root1 == nullptr) return root2;
if (root2 == nullptr) return root1;
// 单层递归逻辑
if (root1 != nullptr && root2!= nullptr) {
root1->val = root1->val + root2->val;
}
root1->left = traversal (root1->left, root2->left);
root1->right = traversal (root1->right, root2->right);
return root1;
}
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
return traversal (root1, root2);
}
};
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == nullptr) return nullptr;
if (val == root->val) return root;
return searchBST(val > root->val? root->right : root->left, val);
}
};
解题思路:
- 得到树的中序遍历,检查是否为递增序列即可
class Solution {
public:
void traversal (TreeNode* cur) {
if (cur == nullptr) return;
traversal(cur->left);
value_vec.push_back(cur->val);
traversal(cur->right);
}
bool isValidBST(TreeNode* root) {
traversal(root);
for( int i = 1; i < value_vec.size(); i++) {
if( value_vec[i] <= value_vec[i-1]) return false;
}
return true;
}
private:
vector<int> value_vec;
};
// 递归
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root == nullptr) return true;
bool left = isValidBST(root->left);
if (max_value < root->val) max_value = root->val;
else return false;
bool right = isValidBST(root->right);
return left && right;
}
private:
long long max_value = LONG_MIN;
};