LeetCode 113. 路径总和 II

题目链接:https://leetcode-cn.com/problems/path-sum-ii/

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22,

5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:

[
[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     void deal(TreeNode* root,vector<vector<int>>& res,vector<int> cur,int sum){
13         if(root==NULL) return;
14         sum-=root->val;
15         cur.push_back(root->val);
16         if(root->left==NULL&&root->right==NULL){
17             if(sum==0) res.push_back(cur);
18         }
19         deal(root->left,res,cur,sum);
20         deal(root->right,res,cur,sum);
21     }
22     vector<vector<int>> pathSum(TreeNode* root, int sum) {
23         vector<vector<int>> res;
24         vector<int> cur;
25         deal(root,res,cur,sum);
26         return res;
27     }
28 };

 

posted @ 2020-04-11 18:40  wydxry  阅读(294)  评论(0编辑  收藏  举报
Live2D