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 — #1609 - Even Odd Tree - LeetCode JavaScript Solutions

Back to all solutions

#1609 - Even Odd Tree

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

Problem Description

A binary tree is named Even-Odd if it meets the following conditions:

  • The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
  • For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
  • For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).

Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.

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 isEvenOddTree = function(root) {
  let queue = [root];
  let level = 0;

  while (queue.length) {
    const levelSize = queue.length;
    let prevValue = level % 2 === 0 ? -Infinity : Infinity;
    const newQueue = [];

    for (let i = 0; i < levelSize; i++) {
      const node = queue[i];
      const isEvenLevel = level % 2 === 0;
      const isOddValue = node.val % 2 === 1;

      if (isEvenLevel && (!isOddValue || node.val <= prevValue)) return false;
      if (!isEvenLevel && (isOddValue || node.val >= prevValue)) return false;

      prevValue = node.val;
      if (node.left) newQueue.push(node.left);
      if (node.right) newQueue.push(node.right);
    }

    queue = newQueue;
    level++;
  }

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