1.路径总和(1)
题目链接:https://leetcode-cn.com/problems/path-sum
题目描述:
给你二叉树的根节点 root 和一个表示目标和的整数 targetSum ,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。
叶子节点 是指没有子节点的节点。
题解:
采用DFS遍历路径,使用递归方式。递归函数的参数和返回值的确定:如果需要搜索整颗二叉树,那么递归函数就不要返回值,如果要搜索其中一条符合条件的路径,递归函数就需要返回值,因为遇到符合条件的路径了就要及时返回。
题解:
/**
* 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 {
public:
bool travel(TreeNode* node, int count)
{
if(node->left == nullptr && node->right == nullptr && count == 0) //节点为叶子节点,且总和值相等
return true;
if(node->left)
{
count -= node->left->val; //递归,处理节点
if(travel(node->left, count)) return true;
count += node->left->val; //回溯,撤销先前的操作
}
if(node->right)
{
count -= node->right->val;
if(travel(node->right, count)) return true;
count -= node->right->val;
}
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root == nullptr)
return false;
return travel(root, targetSum - root->val);
}
};
2.全部路径(2)
题目链接:https://leetcode-cn.com/problems/path-sum-ii/
题目描述:
题解:
由上一题的练习,这一题的递归函数的返回值为void,参数与上一题相同,代码逻辑与上一题也基本相同,只是当遍历到一条路径后需要存放在vector中。
/**
* 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 {
vector<vector<int>> result;
vector<int> vec;
public:
void travel(TreeNode* node, int count)
{
if(node->left == nullptr && node->right == nullptr && count == 0)
{
result.push_back(vec); //找到一条符合要求的路径,存入结果vector中
}
if(node->left)
{
vec.push_back(node->left->val); //迭代,节点操作
count -= node->left->val; //迭代,节点操作
travel(node->left, count);
count += node->left->val; //回溯,撤销节点操作
vec.pop_back(); //回溯,撤销节点操作
}
if(node->right)
{
vec.push_back(node->right->val);
count -= node->right->val;
travel(node->right, count);
count += node->right->val;
vec.pop_back();
}
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum)
{
if(root == nullptr)
return result;
vec.push_back(root->val);
travel(root, targetSum - (root->val));
return result;
}
};