题目描述
题目链接: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 path5->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
代码如下:
/**
* 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