版权声明:本文为博主原创文章,欢迎转载!转载请保留原博客地址。 https://blog.csdn.net/grllery/article/details/85252888
112. Path Sum
[Easy] 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.
Note: A leaf is a node with no children.
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到叶子结点上的元素和等于sum的情况。如果是,返回true。
注意必须是从根结点开始。
递归。直觉上就是如果需要求根结点root到叶子结点的和为某个sum,那就判断根结点的左孩子->叶子结点的和是否为sum-root.val,或者root的右孩子->叶子结点的和是否是否为root.val,依次递归下去。
递归开始的条件:当遇到了非叶子的结点,对左孩子和有孩子分别进行递归。进入递归时,需要比对的目标sum应该是在当前的目标值上减去该结点对应的值。
递归返回的条件:当遇到了空指针或者遇到了叶子结点。
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) {
return helper(root, sum);
}
private:
bool helper(TreeNode* root, int remain) {
if (root == nullptr)
return false;
remain -= root->val;
if (root->left == nullptr && root->right == nullptr)
{
if (remain == 0)
return true;
else
return false;
}
bool left = helper(root->left, remain);
bool right = helper(root->right, remain);
return left || right;
}
};