654.最大二叉树
1. 偷懒直接用了内置的函数
最大值:int maxValue = *max_element(v.begin(),v.end()); 返回的是迭代器
最大值下标:int maxPosition = max_element(v.begin(),v.end()) - v.begin();
2. vector容器取切片的方法
vector<int> numright(nums.begin()+1,nums.end()); 用迭代器写
class Solution {
private:
TreeNode* findMax(vector<int>& nums){
if (nums.size()==0) return NULL;
int max = *max_element(nums.begin(), nums.end());
TreeNode *root=new TreeNode(max);
//if(nums.size()==1) return root;
int max_index=max_element(nums.begin(),nums.end())-nums.begin();
if(max_index==0)
{
vector<int> numright(nums.begin()+1,nums.end());
root->right=findMax(numright);
}
else if(max_index==nums.size()-1)
{
vector<int> numleft(nums.begin(),nums.end()-1);
root->left=findMax(numleft);
}
else
{
vector<int> numleft(nums.begin(),nums.begin()+max_index);
vector<int> numright(nums.begin()+1+max_index,nums.end());
root->right=findMax(numright);
root->left=findMax(numleft);
}
return root;
}
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return findMax(nums);
}
};
617.合并二叉树
1. 同时处理两个二叉树,有点陌生,也是一边遍历一边处理,直接传入两个参数就可以了
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
//先遍历二叉树,再处理
if(t1==NULL) return t2;
if(t2==NULL) return t1;
t1->val+=t2->val;
t1->left=mergeTrees(t1->left,t2->left);
t1->right=mergeTrees(t1->right,t2->right);
return t1;
}
};
700.二叉搜索树中的搜索
比较简单
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root==NULL) return NULL;
if(root->val==val) return root;
if(root->val>val) return searchBST(root->left,val);
return searchBST(root->right,val);
}
};