Symmetrical Tree

  • n, h

// This is an input class. Do not edit.
class BinaryTree {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

exports.BinaryTree = BinaryTree;

function symmetricalTree(tree) {
  
  return validate(tree.left, tree.right);
}

function validate(left, right) {
  if (left === null && right === null) {
    return true;
  }

  if (left === null || right === null || left.value !== right.value) {
    return false;
  }

  const outer = validate(left.left, right.right);
  const inner = validate(left.right, right.left);

  return outer && inner;
}

// Do not edit the line below.
exports.symmetricalTree = symmetricalTree;
  • iteration

Last updated