leetcode113. Path sum II

来源:互联网 发布:寻觅直播软件 编辑:程序博客网 时间:2024/06/10 00:41

这道题是path sum I的升级版,通过这道题我发觉我竟然忘了树的一个重要定义。所以在这做一个记录:
题目描述如下:
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]
]

即给了一个总的sum值,要求找到所有从根结点到叶子结点路径和等于sum值的路径。这一点要复习一下什么是叶子结点,这对求和很重要。叶子结点就是没有子结点的结点,在二叉树中没有右节点也没有左结点,知道了这个,方法就简单了,递归深度搜索遍历树,找到符合条件的路径:
这是我的方法:

class Solution {private:    vector<vector<int>> res;    void findpath(TreeNode* root,int sum,vector<int> num)    {        if(!root) return;        num.push_back(root->val);        if((!root->left) && (!root->right) && sum==root->val)        {            res.push_back(num);            return;        }        findpath(root->left,sum-(root->val),num);        findpath(root->right,sum-(root->val),num);    }public:    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<int> temp;        findpath(root,sum,temp);        return this->res;    }};

这里的递归函数,我直接传入了vector num这个形参,而没有用引用是想着避免num要手动进栈出栈的操作。但是确实在递归的使用用vector这样的形参太浪费时间和空间了,因为每次传对象的形参的时候都要调用拷贝构造函数,递归的层数一多就会很棘手,所以,这里参考了一下最高赞答案,还是用了引用的形式:

class Solution {private:    void findpath(TreeNode* root,int sum,vector<vector<int>> &paths,vector<int> &path)    {        if(!root) return;        path.push_back(root->val);        if((!root->left) && (!root->right) && sum==root->val)        {            paths.push_back(path);        }        findpath(root->left,sum-(root->val),paths,path);        findpath(root->right,sum-(root->val),paths,path);        path.pop_back();    }public:    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<vector<int>> paths;        vector<int> path;        findpath(root,sum,paths,path);        return paths;    }};
原创粉丝点击