617.合并二叉树
class Solution {
public:TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {if (root1 == nullptr) return root2;if (root2 == nullptr) return root1;root1->val += root2->val;root1->left = mergeTrees(root1->left, root2->left);root1->right = mergeTrees(root1->right, root2->right);return root1;}
};
700.二叉搜索树中的搜索
class Solution {
public:TreeNode* searchBST(TreeNode* root, int val) {if (root == nullptr || root->val == val) return root;if (root->val > val) return searchBST(root->left, val);if (root->val < val) return searchBST(root->right, val);return nullptr;}
};
98. 验证二叉搜索树
class Solution {
private:vector<int> res;void traversal(TreeNode* root){if (root == nullptr) return;traversal(root->left);res.push_back(root->val);traversal(root->right);}
public:bool isValidBST(TreeNode* root) {res.clear();traversal(root);for (int i = 1; i < res.size(); i++){if (res[i - 1] < res[i]){continue;}else{return false;}}return true;}
};
530.二叉搜索树的最小绝对差
class Solution {
private:vector<int> res;void traversal(TreeNode* root){if (root == nullptr) return;traversal(root->left);res.push_back(root->val);traversal(root->right);}
public:int getMinimumDifference(TreeNode* root) {res.clear();traversal(root);if (res.size() < 2) return 0;int result = INT_MAX;for (int i = 1; i < res.size(); i++){result = std::min(result, res[i] - res[i - 1]);}return result;}
};