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] ]
基本思路:
深度递归。
逐层从sum中扣去当节点的val值。
到叶结点时,检查sum值是否等于该叶结点的val值。若是,则找到一个结果。
在结果集中,用最后一个元素,作为待决结果。随着栈的深入而压入元素,退出则弹出元素。
在leetcode上实际执行时间为18ms。
/**
* 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>> ans(1);
dfs(ans, root, sum);
ans.pop_back();
return ans;
}
void dfs(vector<vector<int> > &ans, TreeNode *root, int sum) {
if (!root) return;
if (!root->left && !root->right && root->val == sum) {
ans.back().push_back(root->val);
ans.push_back(ans.back());
ans.back().pop_back();
return;
}
ans.back().push_back(root->val);
dfs(ans, root->left, sum - root->val);
dfs(ans, root->right, sum - root->val);
ans.back().pop_back();
}
};