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

[LeetCode]Path Sum II

时间:2015-12-19 15:03:46      阅读:111      评论: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]
]

解题思路:

需要遍历所有路径

 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         vector<int> one_result;// 中间结果
15         pathSum(root, result, sum, one_result);
16         return result;
17     }
18 private:
19     void pathSum(TreeNode *root, vector<vector<int>> &result, int sum, vector<int> &one_result) {
20         if (root == nullptr) return;
21         
22         one_result.push_back(root->val);
23         if (root->left == nullptr && root->right == nullptr && sum == root->val) {//叶节点
24             result.push_back(one_result);
25         }
26         pathSum(root->left, result, sum - root->val, one_result);
27         pathSum(root->right, result, sum - root->val, one_result);
28         
29         one_result.pop_back();
30     }
31 };

 

[LeetCode]Path Sum II

标签:

原文地址:http://www.cnblogs.com/skycore/p/5059124.html

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