LeetCode之“树”:Path Sum && Path Sum II

时间:2023-03-09 02:05:57
LeetCode之“树”:Path Sum && Path Sum II

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.

  这道题采用深度优先搜索的方法就可以了,具体程序(12ms)如下:

 /**
* Definition for a binary tree node.
* 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)
return false;
return hasPathSumSub(root, , sum);
} bool hasPathSumSub(TreeNode *tree, int subSum, int sum)
{
if(!tree)
return false; subSum += tree->val;
if(!tree->left && !tree->right && subSum == sum)
return true; return hasPathSumSub(tree->left, subSum, sum) || hasPathSumSub(tree->right, subSum, sum);
}
};

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]
]

  这题与上题类似。具体程序(24ms)如下:

 /**
* Definition for a binary tree node.
* 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>> rVec;
if(!root)
return rVec; vector<int> vec;
hasPathSumSub(root, vec, rVec, , sum);
return rVec;
} void hasPathSumSub(TreeNode *tree, vector<int> vec, vector<vector<int>>& rVec, int subSum, int sum)
{
if(!tree)
return; vec.push_back(tree->val);
subSum += tree->val;
if(!tree->left && !tree->right && subSum == sum)
rVec.push_back(vec); hasPathSumSub(tree->left, vec, rVec, subSum, sum);
hasPathSumSub(tree->right, vec, rVec, subSum, sum);
}
};