Path Sum

原题

https://leetcode.com/problems/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,
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
翻译:给一棵二叉树和一个数值,判断是否有一条从树根到叶节点的路径,使得该路径上的节点的值的和为这个给定值。
如图中,给定22,有 5->4->11->2是符合要求的。

思路

  树的问题,很多用递归的方法解决比较简单,这边就用递归的思想——对于每个节点,无非就是用目标值减去节点本身的值,然后继续寻求一条这样的路径(减去自己的值,就是不包括自己的到叶节点的路径了)。

代码

  问题比较简单,代码应该还是能解释他自己。

/**
 * 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 == NULL) return false;
        return hasSum(root,sum,0);
    }

    bool hasSum(TreeNode* theRoot, int sum, int tempSum)
    {
        if(theRoot->left == NULL && theRoot->right == NULL) return theRoot->val + tempSum == sum;
        if(theRoot->left != NULL)
        {
            if(theRoot->right != NULL)
                return hasSum(theRoot->left,sum,tempSum + theRoot->val) ||  hasSum(theRoot->right,sum,tempSum + theRoot->val);
            else
                return hasSum(theRoot->left,sum,tempSum + theRoot->val);
        }
        else
            return hasSum(theRoot->right,sum,tempSum + theRoot->val);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值