【leetcode】113Path Sum II(DFS输出路径)

来源:互联网 发布:3dsmax2014软件许可证 编辑:程序博客网 时间:2024/05/01 19:55

题目大意:给出一棵二叉树以及一个值sum,找出所有路径上结点和为sum的根到叶结点的路径


用了递归形式的DFS,在递归过程中保存路径信息。

写了两个版本,第一个版本24ms,第二个版本16ms,区别在于第二个版本使用了引用形参,由于不需要每次额外创建vector,提高了一些效率,但需要增加额外的操作。

第一个版本

/** * 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:    void GetPath(TreeNode *root,int sum,vector<vector<int>> &ans,vector<int> tmp)    {        if(!root) return;        sum-=root->val;   //每次sum值减去当前节点值        tmp.push_back(root->val);   //将当前节点的值放入tmp中        if(sum==0&&root->left==NULL&&root->right==NULL) {ans.push_back(tmp);return;}  //若当前节点为叶节点且路径和满足要求,则将记录了一条路径值的tmp加入ans中        GetPath(root->left,sum,ans,tmp);        GetPath(root->right,sum,ans,tmp);    }    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<vector<int>>ans;        int curr=0;        vector<int>tmp;        GetPath(root,sum,ans,tmp);        return ans;    }};

第二个版本

class Solution {public:    void GetPath(TreeNode *root,int sum,vector<vector<int>> &ans,vector<int> &tmp)    {        if(!root) return;        sum-=root->val;        tmp.push_back(root->val);        if(!sum&&root->left==NULL&&root->right==NULL) {ans.push_back(tmp);tmp.pop_back();return;} //由于tmp现在是引用形参,需要手动pop        GetPath(root->left,sum,ans,tmp);        GetPath(root->right,sum,ans,tmp);        tmp.pop_back();    //额外的pop    }    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<vector<int>>ans;        int curr=0;        vector<int>tmp;        GetPath(root,sum,ans,tmp);        return ans;    }};


0 0
原创粉丝点击