Leetcode-112: Path Sum

解法1:分治。
注意这题一定要是从root到leaf,没有到leaf就算出来sum的不算solution。

#include <iostream>
#include <algorithm>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

bool hasPathSum(TreeNode* root, int sum) {
    if (!root) return false;
    if ((root->val==sum) && !root->left && !root->right) return true;
    return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
}

int main()
{
    TreeNode a(5);
    TreeNode b(4);
    TreeNode c(8);
    TreeNode d(11);
    TreeNode e(13);
    TreeNode f(4);
    TreeNode g(7);
    TreeNode h(2);
    TreeNode i(1);

    a.left=&b;
    a.right=&c;
    b.left=&d;
    c.left=&e;
    c.right=&f;
    d.left=&g;
    d.right=&h;
    f.right=&i;

    cout<<hasPathSum(&a, 22)<<endl;

    TreeNode j(1);
    TreeNode k(2);
    j.left=&k;
    cout<<hasPathSum(&j, 1)<<endl;
    return 0;
}

解法2: 遍历。

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        helper(root, targetSum);
        return found;        
    }
private:
    bool found = false;
    void helper(TreeNode *root, int targetSum) {
        if (found || !root) return;
        if (!root->left && !root->right && root->val == targetSum) {
            found = true;
        }
        helper(root->left, targetSum - root->val);
        helper(root->right, targetSum - root->val);
    }
};

解法3:另一种遍历。在前序遍历和后序遍历的位置加代码,也就是回溯算法

class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        target = targetSum;
        helper(root);
        return found;        
    }
private:
    bool found = false;
    int sum = 0, target = 0;
    void helper(TreeNode *root) {
        if (found || !root) return;
        sum += root->val;
        if (!root->left && !root->right && sum == target) {
            found = true;
        }
        helper(root->left);
        helper(root->right);
        sum -= root->val;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值