LeetCode-113. Path Sum II

网友投稿 263 2022-08-29

LeetCode-113. Path Sum II

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​​,

5 / \ 4 8 / / \ 11 13 4 / \ / \7 2 5 1

Return:

[ [5,4,11,2], [5,8,4,5]]

题解:

class Solution {public: void dfs(TreeNode* root, int sum, vector> &res, vector &idx) { if (root == NULL) { return; } idx.push_back(root->val); if (root->left == NULL && root->right == NULL && sum - root->val == 0) { res.push_back(idx); } dfs(root->left, sum - root->val, res, idx); dfs(root->right, sum - root->val, res, idx); idx.pop_back(); } vector> pathSum(TreeNode* root, int sum) { vector> res; vector idx; dfs(root, sum, res, idx); return res; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-110. Balanced Binary Tree
下一篇:完美日记,被自己的营销神话打败!(完美日记成功营销)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~