贪心,被交换的元素,左边应该大于右边,且左边的索引应该尽可能大
class Solution {
public:
vector<int> prevPermOpt1(vector<int>& arr) {
int n = arr.size();
for (int i = n - 2; i >= 0; i--) {
if (arr[i] > arr[i + 1]) {
int j = n - 1;
while (arr[j] >= arr[i] || arr[j] == arr[j - 1]) {
j--;
}
swap(arr[i], arr[j]);
break;
}
}
return arr;
}
};
class Solution {
public:
TreeNode* dfs(int left, int right, vector<int>& nums) {
if (left == right) return nullptr;
int max_index = max_element(nums.begin() + left, nums.begin() + right) - nums.begin();
TreeNode* root = new TreeNode(nums[max_index]);
root->left = dfs(left, max_index, nums);
root->right = dfs(max_index + 1, right, nums);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return dfs(0, nums.size(), nums);
}
};
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == nullptr && root2 == nullptr) return nullptr;
if (root1 == nullptr) return root2;
if (root2 == nullptr) return root1;
TreeNode* root = new TreeNode(root1->val + root2->val);
root->left = mergeTrees(root1->left, root2->left);
root->right = mergeTrees(root1->right, root2->right);
return root;
}
};
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (!root) return nullptr;
if (root->val == val) return root;
if (root->val < val) {
return searchBST(root->right, val);
}
return searchBST(root->left, val);
}
};
class Solution {
public:
long pre = LONG_MIN;
bool isValidBST(TreeNode* root) {
if (root == nullptr) return true;
if (!isValidBST(root->left)) return false;
if (root->val <= pre) return false;
pre = root->val;
return isValidBST(root->right);
}
};