leetcode 37:path-sum-ii
题目描述
给定一个二叉树和一个值 sum\ sum sum,请找出所有的根节点到叶子节点的节点值之和等于 sum\ sum sum 的路径,
例如:
给出如下的二叉树, sum=22\ sum=22 sum=22,
例如:
给出如下的二叉树, sum=22\ sum=22 sum=22,
返回
[
[5,4,11,2],
[5,8,9]
]
[
[5,4,11,2],
[5,8,9]
]
题目分析:这道题和leetcode 22:sum-root-to-leaf-numbers解法基本一致。
代码如下:
1 void GetPathSum(TreeNode* root,vector<vector<int>> &ret,vector<int> &tmp,int &retSum,int sum) 2 { 3 if(root == NULL) 4 return; 5 6 tmp.push_back(root->val); 7 retSum += root->val; 8 if(!root->left&& !root->right) //子节点 9 { 10 if(sum == retSum) 11 ret.push_back(tmp); 12 } 13 else{ 14 if(root->left) 15 GetPathSum(root->left,ret,tmp,retSum,sum); 16 if(root->right) 17 GetPathSum(root->right,ret,tmp,retSum,sum); 18 } 19 retSum -= root->val; 20 tmp.pop_back(); 21 } 22 vector<vector<int> > pathSum(TreeNode* root, int sum) { 23 vector<vector<int>> ret; 24 vector<int> tmp; 25 int retSum = 0; 26 GetPathSum(root,ret,tmp,retSum,sum); 27 return ret; 28 }