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的查找,深搜搜到结果返回即可
1 /**
2 * Definition for binary tree
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 bool hasPathSum(TreeNode *root, int sum) {
13 if(root==NULL) return false;
14 int sumval = root->val;
15 if(sumval==sum && root->left==NULL &&root->right==NULL) return true;
16 else{
17 return (hasPathSum(root->left,sum-sumval)||hasPathSum(root->right,sum-sumval));
18 }
19 }
20 };
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实现),记录已经走过的路径,
返回是栈也弹出相应节点
1 /**
2 * Definition for binary tree
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 bool pathrec(vector<vector<int> > &rec, vector<int>& path,TreeNode* r,int sum)
13 {
14 sum-=r->val;
15 //if(sum<0) return false;
16 //Tell if it‘s a leaf node
17 if(r->left ==NULL && r->right == NULL)
18 {
19 if(sum!=0) return false;
20 else{
21 vector<int> one = path;
22 one.push_back(r->val);
23 rec.push_back(one);
24 return true;
25 }
26 }
27 //Ordinary node
28 path.push_back(r->val);
29 bool flag = false;
30 if(r->left!=NULL) pathrec(rec,path,r->left,sum);
31 if(r->right!=NULL) pathrec(rec,path,r->right,sum);
32 path.erase(path.end()-1);
33 return flag;
34
35 }
36 vector<vector<int> > pathSum(TreeNode *root, int sum) {
37 vector<vector<int> > rec;
38 if(root==NULL) return rec;
39 vector<int> path;
40 pathrec(rec,path,root,sum);
41
42 return rec;
43 }
44 };
Leetcode::Pathsum & Pathsum II,布布扣,bubuko.com
时间: 2024-10-21 21:01:28