`

Path Sum II (C++)

 
阅读更多
/**
 * Definition for binary tree
 * 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<int> tempvec;
        vector<vector<int>> allpath;
        sps(root, sum, tempvec, allpath);
        return allpath;
    }
    
    // train of thought
    //
    void sps(TreeNode* root, int sum, vector<int> &pvec, vector<vector<int>> &allpath) {
        if(!root) return;
        
        if(root->val == sum && !root->left && !root->right) {
            pvec.push_back(root->val);
            allpath.push_back(pvec);
            pvec.pop_back();
            return;
        } 
        
        pvec.push_back(root->val);
        sps(root->left, sum-root->val, pvec, allpath);
        sps(root->right, sum-root->val, pvec, allpath);
        pvec.pop_back();
    }
};

 

欢迎关注微信公众号——计算机视觉:

分享到:
评论

相关推荐

    Leetcode打谱集.pdf

    此外,文档还提到了另一个问题——路径总和II(Path Sum II),这是一个寻找二叉树中特定和的路径的问题。虽然没有给出完整的代码,但可以看出这个问题涉及到递归或深度优先搜索(DFS)的策略,可能需要使用回溯法来...

    LeetCode最全代码

    371 | [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) | [C++](./C++/sum-of-two-integers.cpp) [Python](./Python/sum-of-two-integers.py) | _O(1)_ | _O(1)_ | Easy | LintCode | ...

    leetcode分类-LeetCode:力码

    C++,有详细思路解释 python,部分有解释 Java,部分有解释 Java Associated Documents and Resources Peter norvig神牛Python代码写的很飘逸,果然是有LISP内功的人! 本书涉嫌抄袭leetcode,特此注明 题目分类 from ###...

    Leetcode题目+解析+思路+答案.pdf

    - **Path Sum II**:寻找所有从根节点到叶节点的路径,其路径和等于给定的目标值。 - **Flatten Binary Tree to Linked List**:将二叉树展平为单链表。 - **Validate Binary Search Tree**:验证一个二叉树是否...

    android JNI 学习笔记.doc

    include $(call all-makefiles-under,$(LOCAL_PATH)) ``` 这些指令用于指定项目的名称、JNI共享库的名称以及如何构建项目。 - **JNI目录下的Android.mk文件**:在JNI目录下,也有一个`Android.mk`文件,用于指定...

Global site tag (gtag.js) - Google Analytics