找树左下角的值:
讲解:代码随想录
思路:
通过递归遍历,并且判断是否为叶子节点,每次遍历计算当前结点的深度,当遍历完成后,最深且为叶子节点的
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void caozuo(struct TreeNode*root,int depth,int *result,int *maxdepth)
{
if(root->left==NULL &&root->right==NULL)
{
if(depth>*maxdepth)
{
*maxdepth = depth;
*result=root->val;
}
return;
}
if(root->left)
{
depth++;
caozuo(root->left,depth,result,maxdepth);
depth--;
}
if(root->right)
{
depth++;
caozuo(root->right,depth,result,maxdepth);
depth--;
}
return;
}
int findBottomLeftValue(struct TreeNode* root) {
int maxdepth=INT_MIN;
int result;
caozuo(root,0,&result,&maxdepth);
return result;
}
遇到的问题:
1.对于C语言全局变量的问题:全局变量会增加程序的耦合性
2.递归的回溯:1.手动回溯 2.在调用函数时加一,可以实现自动回溯
路径总和:
讲解:代码随想录
思路:
递归法:因为只需要找是否有符合条件的路径,也就是只需要找到一条就可以结束,所以递归的参数是根节点,和计数器用来记录路径和。递归的中止条件是当遍历到叶子结点时停止,同时要判断这条路径是否满足条件。当找到路径时,就会一直返回true,直到中止所有函数操作
代码:
bool caozuo(struct TreeNode*root ,int count)
{
if (root->left ==NULL && root->right==NULL &&count ==0)
{
return true;
}
if (root->left ==NULL && root->right==NULL )
{
return false;
}
if(root->left)
{
if(caozuo(root->left,count-root->left->val))
{
return true;
}
}
if (root->right)
{
if(caozuo(root->right,count-root->right->val))
{
return true;
}
}
return false;
}
bool hasPathSum(struct TreeNode* root, int targetSum) {
int count = targetSum;
if (root ==NULL)
{
return false;
}
return caozuo(root ,count-root->val);
}
遇到的问题:
1。对于只需要判断有符合条件的路径,对于函数的中止,以及返回值:函数的中止情况是当遇到符合条件的路径会中止遍历,没遇到符合条件的路径会一直遍历,中止是遇到叶子节点。
路径总和 II:
讲解:代码随想录
思路:
递归法:此题的思路与上一题不一样,此题是要求找出所有符合条件的路径,所以当找到一条路径后,不能直接结束遍历
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
vector<int> path;
vector<vector<int>>result;
void caozuo(TreeNode* root,int count)
{
if(root->left == NULL &&root->right==NULL &&count == 0)
{
result.push_back(path);
return;
}
if(root->left == NULL &&root->right==NULL )
{
return;
}
if(root->left)
{
path.push_back(root->left->val);
caozuo(root->left,count-root->left->val);
path.pop_back();
}
if(root->right)
{
path.push_back(root->right->val);
caozuo(root->right,count-root->right->val);
path.pop_back();
}
return;
}
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
result.clear();
path.clear();
int count=targetSum;
if(root == NULL)
{
return result;
}
path.push_back(root->val);
caozuo(root,count-root->val);
return result;
}
};
遇到的问题:
1.对于中止条件的调整,不在找到一条符合条件的路径后就会结束当前递归
788

被折叠的 条评论
为什么被折叠?



