617合并二叉树
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector& nums) {
TreeNode *node=new TreeNode{0};
if(nums.size()==1){
node->val=nums[0];
return node;
}
int maxvalue=0;
int maxvalueIndex=0;
for(int i=0;i<nums.size();i++){
if(nums[i]>maxvalue){
maxvalue=nums[i];
maxvalueIndex=i;
}
}
node->val=maxvalue;
if(maxvalueIndex>0){
vector newVec(nums.begin(),maxvalueIndex+nums.begin());
node->left=constructMaximumBinaryTree(newVec);
}
if(maxvalueIndex<nums.size()-1){
vector newVec(nums.begin()+maxvalueIndex+1,nums.end());
node->right=constructMaximumBinaryTree(newVec);
}
return node;
}
};
617合并二叉树
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == NULL) return root2;
if (root2 == NULL) 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== NULL ||root->val==val) {
return root;
}
if(root->val>val) return searchBST(root->left,val);
if(root->val< val) return searchBST(root->right,val);
return NULL;
}
};
98验证二叉搜索树
class Solution {
public:
long long maxVal=LONG_MIN;
bool isValidBST(TreeNode* root) {
if(root==NULL) return true;
bool left=isValidBST(root->left);
if(maxValval) maxVal=root->val;
else return false;
bool right = isValidBST(root->right);
return left &&right;
}
};