leetcode Path Sum II

来源:互联网 发布:国外游戏直播软件 编辑:程序博客网 时间:2024/06/08 00:43

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

/** * 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 {private:        void find(TreeNode *root,int sum,vector<int> &vec,vector<vector<int>> &ans){            if(root==NULL) return;            vec.push_back(root->val);             sum-=root->val;            if(root->left==NULL && root->right==NULL && sum==0 )                ans.push_back(vec);             find(root->left,sum,vec,ans);            find(root->right,sum,vec,ans);            vec.pop_back();        }public:    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<vector<int>> ans;        vector<int> vec;        find(root,sum,vec,ans);        return ans;    }};
0 0
原创粉丝点击