LeetCode 113. 路径总和 II(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     vector<vector<int>> pathSum(TreeNode* root, int sum) {
13         vector<vector<int>> res;
14         if(root == NULL) return res;
15         vector<int> temp;
16         findPath(root, sum, 0, temp, res);
17         return res;
18     }
19     void findPath(TreeNode* root, int sum, int pathSum, vector<int> temp, vector<vector<int>> &res){
20         if(root->left == NULL && root->right == NULL && root->val + pathSum == sum){
21             temp.push_back(root->val);
22             res.push_back(temp);
23             return;
24         }
25         temp.push_back(root->val);
26         if(root->left) findPath(root->left, sum, pathSum + root->val, temp, res);
27         if(root->right) findPath(root->right, sum, pathSum + root->val, temp, res);
28     }
29 };

猜你喜欢

转载自www.cnblogs.com/wmx24/p/9467288.html