前言
写递归不能试图模拟每层递归,必须相信递归能做到我们想象的功能,然后把问题简化成最深层递归和最外层初始情况。
Leetcode 513 找树左下角的值
题目链接:513. 找树左下角的值 - 力扣(LeetCode)
代码随想录题解:代码随想录 (programmercarl.com)
思路:利用层序遍历,每次都记录每层第一个节点的数值,当层序遍历完了这个结果自然是左下角的值。
代码:
class Solution {
public:
int findBottomLeftValue(TreeNode* root) {
queue<TreeNode*> que;
if(root!=NULL)
{
que.push(root);
}
int result;
while(!que.empty())//层序遍历板子
{
int size=que.size();
for(int i=0;i<size;i++)
{
TreeNode* cur=que.front();
que.pop();
if(i==0)
{
result=cur->val;//记录每层第一个的值
}
if(cur->left!=NULL)
{
que.push(cur->left);
}
if(cur->right!=NULL)
{
que.push(cur->right);
}
}
}
return result;
}
};
Leetcode 112 路径总和
代码随想录题解:代码随想录 (programmercarl.com)
思路:递归+回溯,试一下刚才我说的思路,最深层的时候两种情况:找到路径了就返回true,没找到路径就返回false。第一层情况,传入左右节点,记录值。
代码:
class Solution {
public:
bool fun(TreeNode* root,int targetSum)
{
if(root->left==NULL&&root->right==NULL&&targetSum==0)//找到了路径
{
return true;
}
if(root->left==NULL&&root->right==NULL&&targetSum!=0)//没找到路径
{
return false;
}
if(root->left)//第一层传入左孩子
{
targetSum-=root->left->val;
if(fun(root->left, targetSum))
{
return true;
}
targetSum+=root->left->val;//回溯
}
if(root->right)//第一层传入右孩子
{
targetSum-=root->right->val;
if(fun(root->right,targetSum))
{
return true;
}
targetSum+=root->right->val;//回溯
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root==NULL)
{
return false;
}
return fun(root,targetSum-root->val);
}
};
Leetcode 106 中后序创建二叉树
题目链接:106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)
代码随想录题解:代码随想录 (programmercarl.com)
思路:中序是左中右,后序是左右中。先判断后序是否为空或者为一处理特殊情况,然后进入正常处理逻辑根据后序最后一个中元素,切割中序数组和后序数组,然后继续传入切割后的数组。
代码:
class Solution {
public:
TreeNode* fun(vector<int>& inorder,vector<int>&postorder)
{
if(postorder.size()==0)//后序为空
{
return NULL;
}
int end=postorder.size()-1;
TreeNode* root=new TreeNode(postorder[end]);
if(postorder.size()==1)//后序为1
{
return root;
}
int index;
for(index=0;index<inorder.size();index++)//找出中序中的中节点
{
if(inorder[index]==postorder[end])
{
break;
}
}
vector<int> leftinorder(inorder.begin(),inorder.begin()+index);//切割
vector<int> rightinorder(inorder.begin()+index+1,inorder.end());
postorder.pop_back();
vector<int> leftpostorder(postorder.begin(),postorder.begin()+leftinorder.size());
vector<int> rightpostorder(postorder.begin()+leftinorder.size(),postorder.end());
root->left = fun(leftinorder, leftpostorder);//传入左中序左后序
root->right = fun(rightinorder, rightpostorder);//右中序右后序
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if (inorder.size() == 0 || postorder.size() == 0) return NULL;
return fun(inorder, postorder);
}
};
总结
递归是一个需要时间来理解的算法,明天必须开始数据库和计网的学习了