码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 113. Path Sum II

时间:2016-07-20 19:13:13      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

Leetcode 113. Path Sum II

标签:

原文地址:http://www.cnblogs.com/Deribs4/p/5689419.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!