Leetcode::Pathsum & Pathsum II

时间:2022-04-16 05:13:23

Pathsum

Description:

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.

分析:二叉树root-to-leaf的查找,深搜搜到结果返回即可

 /**
* 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) {
if(root==NULL) return false;
int sumval = root->val;
if(sumval==sum && root->left==NULL &&root->right==NULL) return true;
else{
return (hasPathSum(root->left,sum-sumval)||hasPathSum(root->right,sum-sumval));
}
}
};

PathsumII

Description:

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]
]
分析:这一题和上一题的区别在于不仅需要判断有没有,还需要记录是什么。在深搜的时候维护一个stack(这里用vector实现),记录已经走过的路径,
返回是栈也弹出相应节点
 /**
* 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 pathrec(vector<vector<int> > &rec, vector<int>& path,TreeNode* r,int sum)
{
sum-=r->val;
//if(sum<0) return false;
//Tell if it's a leaf node
if(r->left ==NULL && r->right == NULL)
{
if(sum!=) return false;
else{
vector<int> one = path;
one.push_back(r->val);
rec.push_back(one);
return true;
}
}
//Ordinary node
path.push_back(r->val);
bool flag = false;
if(r->left!=NULL) pathrec(rec,path,r->left,sum);
if(r->right!=NULL) pathrec(rec,path,r->right,sum);
path.erase(path.end()-);
return flag; }
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > rec;
if(root==NULL) return rec;
vector<int> path;
pathrec(rec,path,root,sum); return rec;
}
};