113. Path Sum II

来源:互联网 发布:java栈内存溢出 编辑:程序博客网 时间:2024/06/10 15:01

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]

解答:其实就是深度优先搜索,重点在于解决函数接口问题,传入一个root节点,一个到目前为止的所加的值,一个目标值,一个到目前为止的暂时所存的vector

class Solution {public:    vector<vector<int>> result;    void path(TreeNode* root,int now,int target,vector<int> res)    {        if(root==NULL) return ;        now+=root->val;        res.push_back(root->val);        if(root->left) path(root->left,now,target,res);        if(root->right) path(root->right,now,target,res);        if(now==target&&(root->left==NULL)&&(root->right==NULL)) result.push_back(res);    }    vector<vector<int>> pathSum(TreeNode* root, int sum) {        if(root==NULL) return result;        vector<int> res;        path(root,0,sum,res);        return result;    }};

二刷时是这么做的,更符合我的习惯

/** * 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>> result;    vector<vector<int>> pathSum(TreeNode* root, int sum) {        dfs(root,{},0,sum);        return result;    }    void dfs(TreeNode* root,vector<int> path,int temp,int target)    {        if(!root) return;        temp=temp+root->val;        path.push_back(root->val);        if((temp==target)&&(root->left==NULL&&root->right==NULL))        {            result.push_back(path);            return ;        }        dfs(root->left,path,temp,target);        dfs(root->right,path,temp,target);    }};
0 0
原创粉丝点击