leetcode 113. 路径总和 II

问题描述

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

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

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

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

[
   [5,4,11,2],
   [5,8,4,5]
]

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> ans;
        if(!root)return ans;
        vector<int> path;
        int val = 0;
        findPath(root,sum,ans,path,val);
        return ans;
    }
    void findPath(TreeNode* root, int sum,vector<vector<int>> &ans,vector<int> &path,int val)
    {
        if(!root)return;
        path.push_back(root->val);
        val += root->val;
        if(!root->left && !root->right && val == sum)
        {
            ans.push_back(path);
            return;
        }
        if(root->left)
        {
            findPath(root->left,sum,ans,path,val);
            path.pop_back();
        }
        if(root->right)
        {
            findPath(root->right,sum,ans,path,val);
            path.pop_back();
        }
    }
   
};

结果:

执行用时 :12 ms, 在所有 C++ 提交中击败了86.01%的用户
内存消耗 :23.2 MB, 在所有 C++ 提交中击败了33.56%的用户
posted @ 2020-03-09 09:16  曲径通霄  阅读(108)  评论(0编辑  收藏  举报