学习目标:
- 654.最大二叉树
- 617.合并二叉树
- 700.二叉搜索树中的搜索
- 98.验证二叉搜索树
学习内容:
654.最大二叉树
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
//确定递归条件
//题目中说了nums.length>=1,所以不为空,可以不考虑空的情况。
//数组的大小=1的时候,代表到了叶子结点,递归结束。
TreeNode* node = new TreeNode(0);
if(nums.size()==1)
{
node->val=nums[0];
return node;
}
int maxvalue=0;
int index=0;//用来存储maxvalue的下标
for(int i = 0;i<nums.size();i++)
{
if(nums[i]>maxvalue)
{
maxvalue=nums[i];
index = i;
}
}
//这里就应该直接赋值给node,因为node就是设定的根节点。
node->val = maxvalue;
if(index>0)
{
vector<int> leftvector(nums.begin(),nums.begin()+index);
node->left = constructMaximumBinaryTree(leftvector);
}
if(index<(nums.size()-1))
{
vector<int> rightvector(nums.begin()+index+1,nums.end());
node->right = constructMaximumBinaryTree(rightvector);
}
return node;
}
};
错误以及注意事项
- 在找最大值设定为根节点的时候,先想的是又新建一个TreeNode作为root,后来反应过来,开头新建的node就是每个小分支的根节点。
- 优化方法:在左右分支中新建了数组来存储,这是很耗费效率的。可以传入左右index来改。
- 一般情况来说:如果让空节点(空指针)进入递归,就不加if,如果不让空节点进入递归,就加if限制一下, 终止条件也会相应的调整。
617.合并二叉树
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
// 确定终止条件
if(root1==nullptr) return root2;
if(root2==nullptr) return root1;
//不定义新的树,直接改tree1的结构
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==nullptr || root->val ==val) return root;
TreeNode* result = nullptr;
if(root->val > val) result=searchBST(root->left,val);
if(root->val < val) result=searchBST(root->right,val);
return result;
}
};
错误以及注意事项
- 第一遍自己写的是这个玩意儿…
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
//确定终止条件
if(root==nullptr&&root->val!=val) return nullptr;
if(root->val == val) return root;
if(root->val > val) searchBST(root->left,val);
if(root->val < val) searchBST(root->right,val);
return nullptr;
}
};
98.验证二叉搜索树
学习时间:
2023.12.19 20:40-22:00
今天跑了MoCov3的一个mnist小代码,github上的作者是使用的resnet50作为backbone。vit里设定的尺寸大小是224 224, 因为patch设定为16的话,可以整除。我自己的框架整个框架都很晕,还没想明白很多事情,感觉现在只是单纯地想合起来毕业。有点难过。