GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #112 - Path Sum - LeetCode JavaScript Solutions

Back to all solutions

#112 - Path Sum

Easy • View on LeetCode • View on GitHub
Depth-First Search Tree Breadth-First Search Binary Tree

Problem Description

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.

Solution

/**
 * 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) {
    return false;
  }
  const result = [];

  traverse(result, root);

  return result.includes(targetSum);
};

function traverse(result, node, sum = 0) {
  if (!node.left && !node.right) {
    result.push(sum + node.val);
  }

  if (node.left) traverse(result, node.left, sum + node.val);
  if (node.right) traverse(result, node.right, sum + node.val);
}
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.