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

Path Sum II

时间:2015-08-01 23:27:33      阅读:114      评论:0      收藏: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]
]

 

Analyse: recursively do the left and right part. When a fraction meets the requirement, push it into the result.

Runtime: 12ms.

 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     vector<vector<int> > pathSum(TreeNode* root, int sum) {
13         vector<vector<int> > result;
14         if(!root) return result;
15         
16         vector<int> temp;
17         path(root, sum, result, temp);
18         return result;
19     }
20     void path(TreeNode* root, int gap, vector<vector<int> >& result, vector<int>& temp){
21         if(!root) return;
22         
23         temp.push_back(root->val);
24         if(!root->left && !root->right){
25             if(root->val == gap) result.push_back(temp);
26         }
27         path(root->left, gap - root->val, result, temp);
28         path(root->right, gap - root->val, result, temp);
29         
30         temp.pop_back();
31     }
32 };

 

Path Sum II

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4694861.html

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