【Leetcode】【Medium】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]
]

 

解题:

实用递归的方法,题目很简单,每深一层递归,带入新计算出的需要求的sum值,递归函数需要四个入参:最终返回数组,当前已经经历的路径,当前需要的sum,已经结点指针

由于需要递归多个函数,刚开始为了防止“当前已经经历的路径”出现重复记载,因而没有形参没有使用指针,而完整的传入了整个数组,时间72ms

代码如下:

 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         vector<vector<int> > ret;
14         vector<int> cur_nums;
15         pathSumTree(ret, cur_nums, root, sum);
16         return ret;
17     }
18     
19     void pathSumTree(vector<vector<int> > &ret, vector<int> cur_nums, TreeNode *root, int cur_sum) {
20         if (!root) 
21             return;
22         
23         cur_nums.push_back(root->val);
24         if (!root->left && !root->right && cur_sum - root->val == 0)
25             ret.push_back(cur_nums);
26         
27         pathSumTree(ret, cur_nums, root->left, cur_sum - root->val);
28         pathSumTree(ret, cur_nums, root->right, cur_sum - root->val);
29         return;
30     }
31 };

 

但是将形参设置为指针后,代码运行时间大大减少了,因为传递指针比传递整个数组高效多了;

为了防止出现混乱,可以在每次路径考察结束后,将当前的结点从数组中pop出来,避免重复;

代码如下,这次只需要不到20ms:

 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         vector<vector<int> > ret;
14         vector<int> cur_nums(0);
15         pathSumTree(ret, cur_nums, root, sum);
16         return ret;
17     }
18     
19     void pathSumTree(vector<vector<int> > &ret, vector<int> &cur_nums, TreeNode *root, int cur_sum) {
20         if (!root) 
21             return;
22         
23         cur_nums.push_back(root->val);
24         if (!root->left && !root->right && cur_sum - root->val == 0) {
25             ret.push_back(cur_nums);
26             cur_nums.pop_back();
27             return;
28         }
29         
30         pathSumTree(ret, cur_nums, root->left, cur_sum - root->val);
31         pathSumTree(ret, cur_nums, root->right, cur_sum - root->val);
32         cur_nums.pop_back();
33         return;
34     }
35 };

 

posted @ 2015-02-05 23:48  胡潇  阅读(152)  评论(0编辑  收藏  举报