回溯算法

二叉树根节点到叶子节点和为指定值的路径

http://www.nowcoder.com/questionTerminal/840dd2dc4fbd4b2199cd48f2dadf930a

class Solution {
public:
/*
*
* @param root TreeNode类
* @param sum int整型
* @return int整型vector<vector<>>
*/
void DFS(vector<vector<int>>& ans,vector<int> res,TreeNode</int></int>
root,int sum)
{
if(!root) return ;
res.push_back(root->val);
if(root->val == sum && !root->left && !root->right)
ans.push_back(res);
DFS(ans,res,root->left,sum-root->val);
DFS(ans,res,root->right,sum-root->val);
}

vector<vector<int> > pathSum(TreeNode* root, int sum) {
    vector<vector<int>> ans;
    vector<int> res;
    DFS(ans,res,root,sum);
    return ans;
}

};

全部评论

相关推荐

11-15 13:12
已编辑
门头沟学院 Java
斯卡蒂味的鱼汤:知道你不会来数马,就不捞你😂最近数马疯狂扩招,招聘要求挺低的,你能力肯定够,应该就是因为太强了,知道你不会来才不捞你
投递腾讯云智研发等公司10个岗位
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务