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 — #663 - Equal Tree Partition - LeetCode JavaScript Solutions

Back to all solutions

#663 - Equal Tree Partition

Medium • View on LeetCode • View on GitHub
Depth-First Search Tree Binary Tree

Problem Description

Given the root of a binary tree, return true if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree.

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
 * @return {boolean}
 */
var checkEqualTree = function(root) {
  const subtreeSums = new Set();
  const totalSum = calculateSum(root);

  return totalSum % 2 === 0 && subtreeSums.has(totalSum / 2);

  function calculateSum(node) {
    if (!node) return 0;

    const leftSum = calculateSum(node.left);
    const rightSum = calculateSum(node.right);
    const currentSum = node.val + leftSum + rightSum;

    if (node !== root) {
      subtreeSums.add(currentSum);
    }

    return currentSum;
  }
};
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.