文章链接:
654
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include<vector>
#include<climits>
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return build(nums,0,nums.size()-1);
}
TreeNode* build(std::vector<int>&nums,int lo,int hi){
if(lo > hi){
return nullptr;
}
int index = -1,maxVal = INT_MIN;
for(int i = lo;i <=hi;i++){
if(maxVal < nums[i]){
index = i;
maxVal = nums[i];
}
}
TreeNode* root = new TreeNode(maxVal);
root->left = build(nums,lo,index-1);
root->right = build(nums,index+1,hi);
return root;
}
};
617
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* a, TreeNode* b) {
if(!a && !b) return nullptr;
if(!a) return b;
if(!b) return a;
a->val += b->val;
a->left = mergeTrees(a->left,b->left);
a->right = mergeTrees(a->right,b->right);
return a;
}
};
700
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int target) {
if(root == nullptr){
return nullptr;
}
if(root->val > target){
return searchBST(root->left,target);
}
if(root->val < target){
return searchBST(root->right,target);
}
return root;
}
};
98
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
return isValidBST(root,nullptr,nullptr);
}
bool isValidBST(TreeNode* root,TreeNode* min,TreeNode* max){
if(root == nullptr) return true;
if(min != nullptr && root->val <=min->val) return false;
if(max!= nullptr && root->val >=max->val) return false;
return isValidBST(root->left,min,root)
&& isValidBST(root->right,root,max);
}
};