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

LeetCode113 Path Sum II

时间:2016-11-17 01:12:01      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:tree   分析   efi   help   result   bin   roo   node   str   

Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.(Medium)

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

 

分析:

回溯法处理即可,利用helper函数遍历所有路径,达到sum时添加到result里。

代码:

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

 

LeetCode113 Path Sum II

标签:tree   分析   efi   help   result   bin   roo   node   str   

原文地址:http://www.cnblogs.com/wangxiaobao/p/6071803.html

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