1. 程式人生 > >Path Sum(路徑和)

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 andsum = 22,

return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.

題目大意

給定一個二叉樹和一個sum值,看看是否有一條從根到葉子結點的路徑,使得這條路徑上各個結點的值相加剛好等於sum。

思路

遞迴思路求解,遞迴每條路徑,看是否有一條路徑之和剛好等於sum。

遞迴出口是:
(1)返回為true:當前結點剛好是葉子結點&&sum-當前結點的值為0。
(2)返回為false:root == NULL。

避坑:sum和各個結點值有可能是負數;

程式碼

#include<iostream>
using namespace std;

// Definition for binary tree
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

typedef TreeNode* tree;

bool hasPathSum(TreeNode *root, int sum)
{
    if(root == NULL)return false;

    // 保證該店是葉子結點且加到這兒的和為sum
    if(root->val==sum && root->left==NULL && root->right==NULL)
        return true;

    return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}

int main()
{
    tree t = new TreeNode(-2);
    t->left = new TreeNode(-3);
    cout<<hasPathSum(t, -5)<<endl;
    //cout<<-5-(-2)<<endl;
    return 0;
}

以上。