您的位置:首页 > 其它

LeetCode113. Path Sum II

2016-12-30 22:48 441 查看

LeetCode113. Path Sum II

原题地址

题目描述

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]

]

思路

设置一个二维vector(result)存储最后的结果,另一个一维vector(path)存储每一条路径,当找到一条满足条件的路径的时候,将path加入到result中。 寻找满足条件的路径的方法与112 Path Sum 基本相同。

代码实现

class Solution {
public:
vector<vector<int>> result;

void dfs(TreeNode* node, vector<int> path, int sum){
if(!node) return;
if(!node->left && !node->right && node->val == sum) {
path.push_back(node->val);
result.push_back(path);
}
path.push_back(node->val);
dfs(node->left,path,sum-node->val);
dfs(node->right,path,sum-node->val);
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> path;
dfs(root, path, sum);
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode tree