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

[LeetCode] Path Sum II

时间:2014-11-29 13:03:14      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   on   

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

思路:与http://www.cnblogs.com/vincently/p/4130398.html一样的思路,只不过注意保存路径。
  时间复杂度O(n),空间复杂度O(lgN)
相关题目:《剑指offer》面试题25

 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> > result;
14         if (root == NULL) 
15             return result;
16             
17         vector<int> path;
18         pathSum(root, sum, result, path);
19         
20         return result;
21     }
22     
23     void pathSum(TreeNode *root, int sum, vector<vector<int> > &result, vector<int> &path) {
24         path.push_back(root->val);
25         
26         if (root->left == NULL && root->right == NULL) {
27             if (root->val == sum) {
28                 result.push_back(path);
29             } 
30         } 
31         
32         if (root->left) 
33             pathSum(root->left, sum - root->val, result, path);
34             
35         if (root->right)
36             pathSum(root->right, sum - root->val, result, path);
37         
38         path.pop_back();
39             
40     }
41 };

 

[LeetCode] Path Sum II

标签:style   blog   http   io   ar   color   sp   for   on   

原文地址:http://www.cnblogs.com/vincently/p/4130504.html

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