[Leetcode 34] 113 Path Sum II

Problem:

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]
]

Analysis:

This is tree's DFS problem. Either can use a recursive function or a stack to finish the traversal.

Time complexity is O(n), where n is the number of nodes in the tree;

Code:

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int> > pathSum(TreeNode *root, int sum) {
13         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         vector<int> stack;
16         vector<vector<int> > res;
17          
18         if (root == NULL) return res;
19         
20         helper(root, 0, sum, stack, res);
21         return res;
22     }
23     
24     void helper(TreeNode *node, int pathSum, int sum, vector<int> path, vector<vector<int> > &res) {
25         if (node->left == NULL && node->right == NULL) {
26             if (pathSum+node->val == sum) {
27                 path.push_back(node->val);
28                 res.push_back(path);
29             }
30         }
31         
32         path.push_back(node->val);
33         
34         if (node->left != NULL)
35             helper(node->left, pathSum + node->val, sum, path, res);
36         
37         if (node->right != NULL)
38             helper(node->right, pathSum + node->val, sum, path, res);
39     }
40 };
View Code

Attention:

原文地址:https://www.cnblogs.com/freeneng/p/3096137.html