leetcode#437 Path Sum III

Description:

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent >nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

对于这个题目,我们可以考虑用dp算法来考虑是否要将当前节点作为路径中的一个节点。对于取和不取当前节点,都要再对当前节点的左右儿子递归考察。但是,由于和是连续的,所以我们要用一个变量来记录是否可以跳过当前节点。总之,这道题就是一个简单的递归问题。

/**
 * 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:
    int pathSum(TreeNode* root, int sum) {
        return path(root, sum, true);
    }

    int path(TreeNode* root, int sum, bool flag) {
        if (!root) return 0;
        int here = 0;
        if (root->val == sum) {
            here = 1;
        }
        int left1=0, left2=0, right1=0, right2=0;
        if (root->left) {
            left1 = path(root->left, sum - root->val, false);
            if (flag) left2 = path(root->left, sum, true);
        }
        if (root->right) {
            right1 = path(root->right, sum - root->val, false);
            if (flag) right2 = path(root->right, sum, true);
        }
        return here + left1 + left2 + right1 + right2;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值