题目
Number: 113
Difficulty: Medium
Tags: Tree, Depth-first Search
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
For example:
Given the below binary tree and
sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
题解
求二叉树中和为某一值的路径。
参考《剑指Offer》面试题25.
代码
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> result;
vector<int>ans;
Find(result, ans, root, sum);
return result;
}
void Find(vector<vector<int>> &result, vector<int> &ans, TreeNode* root, int target){
if(!root)
return;
ans.push_back(root->val);
target -= root->val;
if(!root->left && !root->right && !target)
result.push_back(ans);
if(root->left) Find(result, ans, root->left, target);
if(root->right) Find(result, ans, root->right, target);
ans.pop_back();
}