654. 最大二叉树
本题在拿到之后就被困住了:
- 分割,怎么找最大值呢,是用最基本的for循环吗?
- 构建新的数组怎么实现数组的拷贝呢?
- 递归的中间逻辑应该怎么写呢?
拿到题还是没有认真分析就下结论了,没有用递归三部曲分析。
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
TreeNode* node = new TreeNode(0);
if(nums.size()==1)
{
node->val=nums[0];
return node;
} //中间节点的处理条件
int index=0,max=INT_MIN;
for(int i=0;i<nums.size();i++)
{
if(nums[i]>max){
max=nums[i];
index=i;
}
}
node->val = max;
if (index > 0) {
vector<int> newVec(nums.begin(), nums.begin() + index);
node->left = constructMaximumBinaryTree(newVec);
}
if (index < (nums.size() - 1)) {
vector<int> newVec(nums.begin() + index + 1, nums.end());
node->right = constructMaximumBinaryTree(newVec);
}
return node;
}
};
不用总感觉自己写的代码思路奇怪。
617 合并二叉树
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1==nullptr&&root2==nullptr)return root1;
if(root1!=nullptr&&root2==nullptr)return root1;
if(root1==nullptr&&root2!=nullptr)return root2;//终止条件
TreeNode* root3=new TreeNode(0);
root3->val=root1->val+root2->val;
root3->left=mergeTrees(root1->left,root2->left);
root3->right=mergeTrees(root1->right,root2->right);
return root3;
}
};
很简单的递归,用递归三部曲来分析即可
700 二叉搜索树中的搜索
本题遇到了一点点困难,因为递归函数有返回值。这个要自己new出来。
class Solution {
public:
TreeNode* result = NULL;
TreeNode* searchBST(TreeNode* root, int val) {
if(root->left==nullptr&&root->right==nullptr&&root->val!=val)return nullptr;
if(root->val==val)return root;
if(root->left){
result= searchBST(root->left,val);
if(result&&result->val==val)return result;
}
if(root->right){
result= searchBST(root->right,val);
}
return result;
}
};
但是上面的方法并没有利用到搜索树的性质
可以root->val与val进行比较来只让代码走一次递归就好。
98. 验证二叉搜索树
代码很简单,没想到用数组或者用前一个结点和后一个节点进行比较。