Home Leetcode 112 - Path Sum
Post
Cancel

Leetcode 112 - Path Sum

No wonder that recursion is a super fit for solving question of binary tree. Simply setting the base case of true and false, the rest is trivial.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
  if ( root === null ) return false
  if ( root.left === null && root.right === null && targetSum === root.val) return true
  return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val)
};
This post is licensed under CC BY-NC-ND 4.0 by the author.