112. Path Sum

1.問題

  • 給予一個binary tree, 檢查是否有路徑總和等於sum

2.想法

  • 提問確認題意:

    • binary tree的類型

  • function header, parameter

  • test input

  • 觀察

    • DFS直到node == NULL時,只要sum ==0時return true

  • 說明想法

    • 要確認的是"root to leaf的總和"是否等於某值

    • 因此base case有:

      • 當sum為0時回傳true, 當sum < 0時回傳false

      • 當左, 右child都不存在時, 回傳(sum == root->val)

    • 如果通過base case的檢查, 則L->V繼續迭代

      • left, right存在時才繼續迭代

    • 如果以上皆非則回傳false

  • 測試計算複雜度

3.程式碼

/**
 * 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) {
            return false;
        }
        return checkSum(root, sum);
    }
private:
    bool checkSum(TreeNode* root, int sum) {
        if (!root) {
            if (sum == 0) {
                return true;
            } else {
                return false;
            }
        }
        //cout<<sum<<endl;
        if (root->left == NULL && root->right == NULL) {            
            return sum == root->val;        
        }
        
        if (root->left && checkSum(root->left, sum - root->val)) {
            return true;
        }
        if (root->right && checkSum(root->right, sum - root->val)) {
            return true;
        }
        return false;
        
    }
};

4.Performance

Last updated