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

» Solve this problem

[解题报告]
二叉树递归。

[Code]

1:    vector<vector<int> > pathSum(TreeNode *root, int sum) {  
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: vector<vector<int> > collect;
5: vector<int> solution;
6: if(root!=NULL)
7: GetPath(root, sum, 0, solution, collect);
8: return collect;
9: }
10: void GetPath(TreeNode* node, int sum, int cal, vector<int>& solution, vector<vector<int> >& collect)
11: {
12: solution.push_back(node->val);
13: cal += node->val;
14: if(cal == sum && node->left == NULL && node->right == NULL)
15: {
16: collect.push_back(solution);
17: }
18: else
19: {
20: if(node->left != NULL)
21: {
22: GetPath(node->left, sum, cal, solution, collect);
23: }
24: if(node->right != NULL)
25: {
26: GetPath(node->right, sum, cal, solution, collect);
27: }
28: }
29: solution.pop_back();
30: cal -= node->val;
31: return;
32: }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值