0%

[Leetcode]112. Path Sum(C++)

题目描述

题目链接:112. 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.

例子

Input: [5,4,8,11,null,13,4,7,2,null,null,null,1]
Output: 22
Explanation: there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Note

  • A leaf is a node with no children.

解题思路

采用递归方法,执行以下步骤:

  • root 为空,返回 false
  • root 为叶结点且其值等于 sum 返回 true
  • 对其左右节点递归调用 hasPathSum(),将 sum 设为 sum - root->val,其中一棵子树返回 true 即返回 true

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root) return false;
if (!root->left && !root->right && root->val == sum) return true;
return hasPathSum(root->left, sum - root->val) ||
hasPathSum(root->right, sum - root->val);
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(h) 递归深度

GitHub 代码同步地址: 112.PathSum.cpp

其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions