LeetCode:Path Sum I II

LeetCode:Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

递归求解,代码如下:

 /**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(root == NULL)return false;
if(root->left == NULL && root->right == NULL && root->val == sum)
return true;
if(root->left && hasPathSum(root->left, sum - root->val))
return true;
if(root->right && hasPathSum(root->right, sum - root->val))
return true;
return false;
}
};

LeetCode: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]
] 本文地址

同理也是递归求解,只是要保存当前的结果,并且每次递归出来后要恢复递归前的结果,每当递归到叶子节点时就把当前结果保存下来。

 /**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<int> > res;
if(root == NULL)return res;
vector<int> curres;
curres.push_back(root->val);
pathSumRecur(root, sum, curres, res);
return res;
}
void pathSumRecur(TreeNode *root, int sum, vector<int> &curres, vector<vector<int> >&res)
{
if(root->left == NULL && root->right == NULL && root->val == sum)
{
res.push_back(curres);
return;
}
if(root->left)
{
curres.push_back(root->left->val);
pathSumRecur(root->left, sum - root->val, curres, res);
curres.pop_back();
}
if(root->right)
{
curres.push_back(root->right->val);
pathSumRecur(root->right, sum - root->val, curres, res);
curres.pop_back();
}
}
};

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3440044.html

上一篇:微信 小程序 drawImage wx.canvasToTempFilePath wx.saveFile 获取设备宽高 尺寸问题


下一篇:关于事件循环机制event loop