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

LeetCode | 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,
              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.


題目解析:

這道題是到達葉節點的和是否等於sum,中間節點達到不行。也不能全部當成正數來判斷,正如程式碼中註釋掉的部分if(root->val > sum),有負數出現,就會造成錯誤判斷。唯一的成功的地方是:當root->val == sum && root->left == NULL && root->right == NULL 這三個條件同時滿足時返回真。其他情況,繼續遞迴就行,在根指標指向NULL的時候返回假。省去了額外的判斷。

class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if(root == NULL){
            return false;
        }
        /*
        if(root->val > sum)
            return false;
        */
        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);
    }
};

期間出現的錯誤:



由於當輸入是空的時候,不能僅用

if(root == NULL){
    if(sum==0)
        return true;
    return false;
}

第二種錯誤,是不能忽略負數的情況。