Leetcode OJ: Path Sum II

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.

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

上一题只需要判断是否存在,这题则需要列出路径,依旧递归,递归关系如下:

1. 当到叶子节点时,判断节点值是否与对应要求的和相等,相等则返回当前节点值,作为一个路径。

2. pathSum(root, sum) = 当前点 与 (pathSum(root->left, sum - root->val), pathSum(root->right, sum - root->val))路径组合

代码如下:

 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     
13     vector<vector<int> > pathSum(TreeNode *root, int sum) {
14         vector<vector<int> > ret;
15         if (root == NULL)
16             return ret;
17         if (root->val == sum && root->left == NULL && root->right == NULL) {
18             ret.push_back(vector<int>(1, root->val));
19             return ret;
20         }
21         vector<vector<int> > leftSum = pathSum(root->left, sum - root->val);
22         vector<vector<int> > rightSum = pathSum(root->right, sum - root->val);
23         vector<vector<int> >::iterator it2d;
24         for (it2d = leftSum.begin(); it2d != leftSum.end(); ++it2d) {
25             vector<int> tmp(1, root->val);
26             tmp.insert(tmp.end(), (*it2d).begin(), (*it2d).end());
27             ret.push_back(tmp);
28         }
29         
30         for (it2d = rightSum.begin(); it2d != rightSum.end(); ++it2d) {
31             vector<int> tmp(1, root->val);
32             tmp.insert(tmp.end(), (*it2d).begin(), (*it2d).end());
33             ret.push_back(tmp);
34         }
35         return ret;
36     }
37 };
原文地址:https://www.cnblogs.com/flowerkzj/p/3616629.html