[leetcode] Path Sum II

来源:互联网 发布:天猫数据在线直播 编辑:程序博客网 时间:2024/06/04 20:44


/** * Definition for binary tree * 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>> res;        vector<int> resRow;        findPath(res,resRow,root,sum);        return res;    }    void findPath(vector<vector<int>>&res,vector<int>&resRow,TreeNode *root,int sum){        if(root==NULL){            return;        }        resRow.push_back(root->val);        if(root->left==NULL&&root->right==NULL){            if(sum==root->val){                res.push_back(resRow);//在vector尾部添加            }        }else{            findPath(res,resRow,root->left,sum-root->val);            findPath(res,resRow,root->right,sum-root->val);        }        resRow.pop_back();//<span style="color: rgb(51, 51, 51); font-family: arial; font-size: 13px; line-height: 20.020000457763672px;">删除当前vector最末的一个元素</span>    }};


0 0
原创粉丝点击