All files / exercises/valid-binary-search-tree index.ts

77.77% Statements 7/9
82.6% Branches 19/23
100% Functions 2/2
75% Lines 6/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 3724x   2x           12x       5x                   5x                 5x          
import BinaryTree from "@src/data-structures/BinaryTree.ts";
 
export function isValidBST(
  node: BinaryTree<number> | null,
  left: BinaryTree<number> | null = null,
  right: BinaryTree<number> | null = null,
): boolean {
  // Base case: a null subtree is a valid BST
  if (node === null) return true;
 
  // if the left node exists then its value
  // should be less than the parent's value
  Iif (
    left !== null &&
    node.value !== null &&
    left.value !== null &&
    node.value <= left.value
  )
    return false;
 
  // if right node exist then its value
  // should be greater than the parent's value
  Iif (
    right !== null &&
    node.value !== null &&
    right.value !== null &&
    node.value >= right.value
  )
    return false;
 
  // check recursively for every node.
  return (
    isValidBST(node.leftChild, left, node) &&
    isValidBST(node.rightChild, node, right)
  );
}