LeetCode---- 二叉树中,找出和为某值的所有路径

2014-11-24 09:43:00 · 作者: · 浏览: 0

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

分析:

这题并不难。其实就是深搜。

就是可能一开始,觉得函数递归的时候,要传哪些参数下去?要返回那些值??

当有多个返回值的时候怎么办??

Trick: C++ 中可以采用引用,来返回值的功能。


1. 返回值: 多条 paths, 可以将 vector >& result 作为形参; 这样其实 所有的递归函数都共享了这个 vector; 当找到路径时,push_back即可。

2. 需要往下传的参数: sum, 当前的路径;

/**
 * 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
  
    > pathSum(TreeNode *root, int sum) {
        vector
   
     > result; vector
    
      path; MyPathSum(root, sum, path, result); return result; } private: void MyPathSum(TreeNode *root, int sum, vector
     
       &path, vector
      
        > &result) { if(root == NULL) return; path.push_back(root->val); if(root->left == NULL && root->right == NULL){ if(sum == root->val){ result.push_back(path); } } if(root->left){ MyPathSum(root->left, sum - root->val, path, result); } if(root->right){ MyPathSum(root->right, sum - root->val, path, result); } path.pop_back(); } };