LeetCode 113. 路径总和 II

题目链接:

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

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

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

 

posted @ 2019-11-12 12:14  wydxry  阅读(200)  评论(0编辑  收藏  举报
Live2D