Your are given a binary tree in which each node contains a value. Design an algorithm to get all paths which sum to a given value. The path does not need to start or end at the root or a leaf, but it must go in a straight line down.
Have you met this question in a real interview?
Yes
Example
Given a binary tree:
1
/ \
2 3
/ /
4 2
for target =6, return
[
[2, 4],
[1, 3, 2]
]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
vector<vector<int>> binaryTreePathSum2(TreeNode *root, int target) {
// Write your code here
vector<vector<int>> res;
vector<int> buf;
dfs(root, target, buf, res);
return res;
}
void dfs(TreeNode *root, int target, vector<int> &buf, vector<vector<int>> &res) {
if (root == NULL)
return;
buf.push_back(root->val);
int sum = 0;
for (int i = buf.size() - 1; i >= 0; --i) {
sum += buf[i];
if (sum == target) {
vector<int> temp;
for (int j = i; j < buf.size(); ++j)
temp.push_back(buf[j]);
res.push_back(temp);
}
}
dfs(root->left, target, buf, res);
dfs(root->right, target, buf, res);
buf.pop_back();
}
};