题目:
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] ]
算法思想:万能的递归,二叉树的不二选择。
vector > pathSum(TreeNode *root, int sum)
{
if (root == NULL) return vector>();
if (root->left == NULL && root->right == NULL && sum == root->val)
return vector>(1, vector(1, root->val));
vector> res_left = pathSum(root->left, sum-root->val);
vector> res_right = pathSum(root->right, sum-root->val);
for (int i = 0; i < res_left.size(); i++)
res_left[i].insert(res_left[i].begin(), root->val);
for (int i = 0; i < res_right.size(); i++)
{
res_right[i].insert(res_right[i].begin(), root->val);
res_left.push_back(res_right[i]);
}
return res_left;
}
378

被折叠的 条评论
为什么被折叠?



