LeetCode 113. Path Sum II路徑總和 II (C++)

題目:

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.html

Note: A leaf is a node with no children.node

Example:數組

Given the below binary tree and sum = 22,函數

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

Return:spa

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

分析:

和Path Sum的思路同樣,連接在這裏http://www.javashuo.com/article/p-rluaxasn-gw.htmlcode

只不過這道題須要將知足目標和的路徑打印出來,咱們能夠傳入一個空數組,每執行一次函數,便將當前的元素,也就是root->val加入到數組,當知足條件時,將數組傳入進咱們定義好的結果數組當中,須要注意的是,空數組須要傳參,而不是傳引用。htm

程序:

/**
 * 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>> res;
        vector<int> s;
        dfs(root, sum, s, res);
        return res;
    }
    void dfs(TreeNode* root, int sum, vector<int> s, vector<vector<int>> &res){
        if(root == nullptr) return;
        s.push_back(root->val);
        if(root->left == nullptr && root->right == nullptr){
            if(sum == root->val)
                res.push_back(s);
        }
        else{
             dfs(root->left, sum-root->val, s, res);
             dfs(root->right, sum-root->val, s, res);
        }      
    }
};
相關文章
相關標籤/搜索