letcode 分类练习 654. 最大二叉树 617.合并二叉树 700.二叉搜索树中的搜索 98.验证二叉搜索树
- 654. 最大二叉树
- 617.合并二叉树
- 700.二叉搜索树中的搜索
- 98.验证二叉搜索树
654. 最大二叉树
class Solution {
public:
TreeNode* build(vector<int>& nums, int left, int right){
int maxV = INT_MIN;
int index;
if(left> right) return nullptr;
for(int i= left;i<=right;i++){
if(nums[i] > maxV){
maxV = nums[i];
index = i;
}
}
TreeNode* node = new TreeNode(maxV);
node -> left = build(nums, left, index - 1);
node -> right = build(nums, index + 1, right);
return node;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return build(nums, 0, nums.size()-1);
}
};
617.合并二叉树
按照题意,我们可以完成merge操作,创建一个新树按要求合并就行,但是要注意如果树1这里为空树2不为空,树1这里要保留为空继续往下遍历,树2也是同理。
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(!root1 && !root2)return nullptr;
TreeNode* node = new TreeNode(-1);
if(root1 && root2){
node -> val = root1 -> val + root2 -> val;
node -> left = mergeTrees(root1 -> left, root2 -> left);
node -> right = mergeTrees(root1 -> right, root2 -> right);
}else if(!root1 && root2){
node -> val = root2 -> val;
node -> left = mergeTrees(nullptr, root2 -> left);
node -> right = mergeTrees(nullptr, root2 -> right);
}else if(root1 && !root2){
node -> val = root1 -> val;
node -> left = mergeTrees(root1 -> left, nullptr);
node -> right = mergeTrees(root1 -> right, nullptr);
}
return node;
}
};
700.二叉搜索树中的搜索
按照二叉搜索树的性质搜就行了
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(!root) return nullptr;
else if(root -> val == val) return root;
else if(root -> val > val) return searchBST(root -> left, val);
else if(root -> val < val) return searchBST(root -> right, val);
return nullptr;
}
};
98.验证二叉搜索树
验证二叉搜索树,一定要有一个左右界来判断
class Solution {
public:
bool valid = true;
void dfs(TreeNode* root, long min, long max){
if(!root) return;
if(root -> val >= max || root -> val <= min){valid = false; return;}
dfs(root -> left, min, root -> val);
dfs(root -> right, root -> val, max);
}
bool isValidBST(TreeNode* root) {
dfs(root, LONG_MIN, LONG_MAX);
return valid;
}
};