Path Sum
AC Rate: 872/2770
My Submissions
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) {
if (root == NULL) return false;
if (root->left == NULL && root->right == NULL ) {
if (root->val == sum) return true;
else return false;
}
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};
Path Sum II
AC Rate: 691/2584
My Submissions
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) {
vector<vector<int> > res;
if (root == NULL) return res;
vector<int> v;
gen(res, v, root, 0, sum);
return res;
}
void gen(vector<vector<int> >& res, vector<int>& v, TreeNode* cur, int s, int sum) {
v.push_back(cur->val);
if (cur->left == NULL && cur->right == NULL) {
if (s+cur->val == sum) res.push_back(v);
}
else {
if (cur->left != NULL) gen(res, v, cur->left, s + cur->val, sum);
if (cur->right!= NULL) gen(res, v, cur->right,s + cur->val, sum);
}
v.pop_back();
}
};

本文探讨了二叉树中寻找特定和的路径问题,包括确定是否存在从根到叶节点的路径使得路径上的数值之和等于给定值,以及找出所有这样的路径。通过递归算法实现解决方案。
1197

被折叠的 条评论
为什么被折叠?



