題目鏈接
tag:
- Medium烹笔;
question:
??Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
Return:
[
[5,4,11,2],
[5,8,4,5]
]
思路:
??用深度優(yōu)先搜索DFS茎毁,每當(dāng)DFS搜索到新節(jié)點(diǎn)時(shí)音念,都要保存該節(jié)點(diǎn)。而且每當(dāng)找出一條路徑之后,都將這個(gè)保存為一維vector的路徑保存到最終結(jié)果二位vector中。并且,每當(dāng)DFS搜索到子節(jié)點(diǎn)虱歪,發(fā)現(xiàn)不是路徑和時(shí),返回上一個(gè)結(jié)點(diǎn)時(shí)瘫里,需要把該節(jié)點(diǎn)從一維vector中移除实蔽。代碼如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int>> res;
vector<int> out;
helper(root, sum, out, res);
return res;
}
void helper(TreeNode* node, int sum, vector<int>& out, vector<vector<int>>& res) {
if (!node) return;
out.push_back(node->val);
if (sum == node->val && !node->left && !node->right) {
res.push_back(out);
}
helper(node->left, sum - node->val, out, res);
helper(node->right, sum - node->val, out, res);
out.pop_back();
}
};
類似題目: