January 17, 2024

Viiisit [LeetCode] - 112. Path Sum

#php#javascript#ruby

keep learning, keep coding!

Problem - Path Sum

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

翻譯蒟蒻

給定一個二元樹的根節點和一個整數目標總和(targetSum),如果該樹具有從根到葉節點的路徑,使得沿著該路徑的所有值相加等於目標總和,則返回true;否則返回false。



Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} targetSum
* @return {boolean}
*/
var hasPathSum = function(root, targetSum) {
if (root === null) {
return false;
}

if (root.left === null && root.right === null) {
// 檢查目標和減去葉節點的值是否為 0,如果為 0,則找到了一條路徑,其節點值的和等於目標和,返回 true
return targetSum - root.val === 0;
}

return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
};

Solution - Ruby

1
2
3
4
5
def has_path_sum(root, target_sum)
return false if root.nil?
return true if root.left.nil? && root.right.nil? && root.val == target_sum
return has_path_sum(root.left, target_sum - root.val) || has_path_sum(root.right, target_sum - root.val)
end

Solution - PHP

1
2
3
4
5
function hasPathSum($root, $targetSum) {
if ($root == null) return false;
if ($root->left == null && $root->right == null) return $targetSum == $root->val;
return $this->hasPathSum($root->left, $targetSum - $root->val) || $this->hasPathSum($root->right, $targetSum - $root->val);
}

LeetCode 傳送門 - Path Sum