二叉树中和为某一值的路径

in 知识共享 with 0 comment

题目来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

叶子节点 是指没有子节点的节点。

示例 1:
请输入图片描述

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]

示例 2:
pathsum2.jpg

输入:root = [1,2,3], targetSum = 5
输出:[]

示例 3:

输入:root = [1,2], targetSum = 0
输出:[]

本人提交代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void findPath( TreeNode* root, int target, int& currSum, vector<int>& path, vector<vector<int>>& result )
    {
        if ( !root )
            return;

        path.push_back( root->val );
        currSum += root->val;
        if ( currSum == target && !root->left && !root->right )
            result.push_back( path );

        findPath( root->left, target, currSum, path, result );
        findPath( root->right, target, currSum, path, result );

        currSum -= root->val;
        path.pop_back();
    }

    vector<vector<int>> pathSum(TreeNode* root, int target) {
        vector<vector<int>> result;
        int currSum = 0;
        vector<int> path;
        findPath( root, target, currSum, path, result );
        return result;
    }
};
Responses