654.最大二叉树
题目链接/文章讲解:代码随想录
解题思路
这道题和构造二叉树本质上没有区别,注意终止条件和进入递归前的条件判断即可
class Solution {
public:
TreeNode* construct(vector<int>& nums, int left , int right)
{
if(left==right-1) return new TreeNode(nums[left]); //遇到叶子节点就返回,左闭右开
//中的处理逻辑
int maxValue = 0;
int index;
for(int i=left;i<right;i++)
{
if(nums[i]>maxValue)
{
index = i;
maxValue = nums[i];
}
}
TreeNode* node = new TreeNode(maxValue);
//左,确保比left大,如果等于,就只有一个元素,已经在上面返回了
if(index>left) node->left = construct(nums,left,index);
//右,必须确保index比right-1还要小,如果等于,就只有一个已经在上面返回了
if(index<right-1) node->right = construct(nums,index+1,right);
return node;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return construct(nums,0,nums.size());
}
};
617.合并二叉树
题目链接/文章讲解: 代码随想录
解题思路
第一次去理解同时处理两个树,我们传参数同时传入两个树的根节点,就是同步进行,随后利用中左右的遍历顺序递归处理即可
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1==nullptr) return root2;
if(root2==nullptr) 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 {
private:
vector<int> result;
public:
TreeNode* search(TreeNode* node, int val)
{
if(node==nullptr) return nullptr;
//单层处理逻辑
if(node->val ==val)
{
return node;
}
TreeNode* result;
if(node->val>val) result = search(node->left,val);
if(node->val<val) result = search(node->right,val);
return result;
}
TreeNode* searchBST(TreeNode* root, int val) {
return search(root,val);
}
};
迭代法
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while(root!=nullptr)
{
if(val<root->val) root = root->left;
else if(val>root->val) root = root->right;
else return root;
}
return nullptr;
}
};
98.验证二叉搜索树
题目链接/文章讲解: 代码随想录
解题思路
首先想到的是二叉搜索树的特性,利用中序即可,但这题还是有坑的,就是我们必须保证左子树所有节点都比当前节点小,右子树所有节点都比当前节点大。
class Solution {
private:
TreeNode* pre;
public:
bool isValidBST(TreeNode* root) {
if(root ==nullptr) return true;
bool left = isValidBST(root->left); //左
if(pre!=nullptr && pre->val >= root->val) //中
{
return false;
}
else
{
pre = root ;
}
bool right = isValidBST(root->right); //右
return left&&right;
}
};
收获
对于递归理解还是不透彻,自己写不出来qwq