leetcode 链接:剑指 Offer 34. 二叉树中和为某一值的路径
本题同:
[中等] 113. 路径总和 II
题目
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 target = 22,
5/ \4 8/ / \11 13 4/ \ / \7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
解答 & 代码
/**
* 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:
void findPaths(TreeNode* cur, int target, vector<int>& path, vector<vector<int>>& resultList)
{
if(cur == nullptr) // 递归结束条件
return;
path.push_back(cur->val); // 选择当前节点作为路径的一点
// 如果当前为叶节点
if(cur->left == nullptr && cur->right == nullptr)
{
if(cur->val == target)
resultList.push_back(path);
}
else // 如果不是叶节点,则递归左、右子树
{
if(cur->left != nullptr)
findPaths(cur->left, target - cur->val, path, resultList);
if(cur->right != nullptr)
findPaths(cur->right, target - cur->val, path, resultList);
}
path.pop_back(); // 回溯,当前节点不作为路径的一点
}
public:
vector<vector<int>> pathSum(TreeNode* root, int target) {
vector<int> path;
vector<vector<int>> resultList;
findPaths(root, target, path, resultList);
return resultList;
}
};
执行结果:通过
执行用时:12 ms, 在所有 C++ 提交中击败了 59.89% 的用户
内存消耗:19.4 MB, 在所有 C++ 提交中击败了 46.53% 的用户
