654.最大二叉树
class Solution {
public:
TreeNode* traversal(vector<int>& nums,int left, int right){
if(left >= right) return nullptr;
int index = left;
for(int i=left+1;i<right;i++){
if(nums[i]>nums[index]) index = i;
}
TreeNode* node = new TreeNode(nums[index]);
node->left = traversal(nums,left,index);
node->right = traversal(nums,index+1,right);
return node;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return traversal(nums,0,nums.size());
}
};
617.合并二叉树
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1 == nullptr) return root2;
if(root2 == nullptr) return root1;
TreeNode* root = new TreeNode(0);
root->val = root1->val + root2->val;
root->left = mergeTrees(root1->left , root2->left);
root->right = mergeTrees(root1->right , root2->right);
return root;
}
};
700.二叉搜索树中的搜索
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root == nullptr || root->val == val) return root;
TreeNode* result = nullptr;
if(root->val < val) result = searchBST(root->right,val);
if(root->val > val) result = searchBST(root->left,val);
return result;
}
};
98.验证二叉搜索树
class Solution {
public:
TreeNode* pre = nullptr;
bool isValidBST(TreeNode* root) {
if(root == nullptr) return true;
bool left = isValidBST(root->left);
if(pre != nullptr && pre->val >= root->val) return false;
pre = root;
bool right = isValidBST(root->right);
return left && right;
}
};