leetcode-剑指 Offer 34. 二叉树中和为某一值的路径
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 target = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
提示:
节点总数 <= 10000
解题思路:
很容易想到本题需要使用深搜,遍历二叉树的每一条从根节点到叶子节点的路径。
class Solution {
vector<vector<int>> ans;
vector<int> path;
void dfs(TreeNode *root,int target,int sum)
{
if(!root) return ;
path.push_back(root->val);
if(!root->left&&!root->right&&sum+root->val==target) //终止条件:必须是从根到叶节点
ans.push_back(path);
dfs(root->left,target,sum+root->val);
dfs(root->right,target,sum+root->val);
path.pop_back();
}
public:
vector<vector<int>> pathSum(TreeNode* root, int target) {
ans.clear();
path.clear();
dfs(root,target,0);
return ans;
}
};