Leetcode 113. Path Sum II

113. Path Sum II

  • Total Accepted: 88034
  • Total Submissions: 302190
  • Difficulty: Medium

 

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

 

 

思路:和Leetcode 257. Binary Tree Paths类似。

 

代码:

不用回溯的形式:24 ms

 1 /**
 2  * Definition for a binary tree node.
 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     void pathSum(vector<vector<int>>& res,TreeNode* root, vector<int> temp, int sum){
13         temp.push_back(root->val);
14         sum-=root->val;
15         if(!root->left&&!root->right&&!sum){
16             res.push_back(temp);
17             return;
18         }
19         if(root->left) pathSum(res,root->left,temp,sum);
20         if(root->right) pathSum(res,root->right,temp,sum);
21     }
22     vector<vector<int> > pathSum(TreeNode* root, int sum) {
23         vector<vector<int> > res;
24         vector<int> temp;
25         if(root) pathSum(res,root,temp,sum);
26         return res;
27     }
28 };

 

用回溯的形式:16 ms

 1 /**
 2  * Definition for a binary tree node.
 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     void pathSum(vector<vector<int>>& res,TreeNode* root, vector<int>& temp, int sum){
13         temp.push_back(root->val);
14         sum-=root->val;
15         if(!root->left&&!root->right&&!sum){
16             res.push_back(temp);
17         }
18         if(root->left) pathSum(res,root->left,temp,sum);
19         if(root->right) pathSum(res,root->right,temp,sum);
20         temp.pop_back();
21     }
22     vector<vector<int> > pathSum(TreeNode* root, int sum) {
23         vector<vector<int> > res;
24         vector<int> temp;
25         if(root) pathSum(res,root,temp,sum);
26         return res;
27     }
28 };

 

posted @ 2016-07-20 18:56  Deribs4  阅读(185)  评论(0编辑  收藏  举报