还是递归搞定!记录一下路径就ok了
/** * 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>>ve; vector<int>vec; void get(TreeNode* root, int sum){ if(root == NULL) return ; if(sum - root -> val == 0 && root -> left == NULL && root -> right == NULL){ vec.push_back(root -> val); ve.push_back(vec); vec.pop_back(); return ; } vec.push_back(root -> val); get(root -> left, sum - root -> val); get(root -> right, sum - root -> val); vec.pop_back(); return ; } vector<vector<int>> pathSum(TreeNode* root, int sum) { get(root, sum); return ve; }新闻热点
疑难解答