112. Path Sum

透過遞迴的方式逐步遞減目標值,直到最後一個節點檢查是否相同

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {
    /**
     * @param TreeNode $root
     * @param Integer $targetSum
     * @return Boolean
     */
    function hasPathSum($root, $targetSum) {
        if ($root === null){
            return false;
        }
        // 最後一個節點的數字與目標數字相同
        if ($root->left == null && $root->right == null) {
            return $root->val === $targetSum;
        }

        $left = $this->hasPathSum($root->left, $targetSum - $root->val);
        $right = $this->hasPathSum($root->right, $targetSum - $root->val);
        
        return $left || $right;
    }
}

Last updated