leetcode-113. Path Sum II
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的路径链。(112升级版)
思路:君可曾记得引用传参result?(这不就搞定了吗!哈哈哈)
Accepted Code:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> pathSum(TreeNode* root, int sum) { 13 vector<vector<int>> result; 14 vector<int> tempResult; 15 pathSum(root,sum,result,tempResult); 16 return result; 17 } 18 19 void pathSum(TreeNode* root,int sum,vector<vector<int>>& result,vector<int>& tempResult) 20 { 21 if(root==nullptr) 22 return; 23 tempResult.push_back(root->val); 24 if(root->left==nullptr&&root->right==nullptr&&sum==root->val){ 25 result.push_back(vector<int>(tempResult)); 26 tempResult.erase(tempResult.end()-1); 27 return; 28 }else 29 { 30 pathSum(root->left,sum-root->val,result,tempResult); 31 pathSum(root->right,sum-root->val,result,tempResult); 32 } 33 tempResult.erase(tempResult.end()-1); 34 } 35 };