Bird
Raised Fist0
DSA Typescriptprogramming

Validate if Tree is BST in DSA Typescript

Choose your learning style10 modes available
Mental Model
A binary search tree (BST) is a tree where every node's left child is smaller and right child is bigger than the node itself. We check this by making sure all nodes follow this rule from top to bottom.
Analogy: Imagine a family tree where every parent is older than their children on the right side and younger than their children on the left side. To check if the tree is correct, you verify each parent's age fits this rule with their children.
      5
     / \
    3   7
   / \   \
  2   4   8
Dry Run Walkthrough
Input: Tree: 5 -> left 3, right 7; 3 -> left 2, right 4; 7 -> right 8
Goal: Check if this tree follows BST rules where left < node < right for all nodes
Step 1: Start at root 5 with allowed range (-∞, +∞)
Node=5, Range=(-∞, +∞)
Why: We begin checking from the root with no limits
Step 2: Check left child 3 with range (-∞, 5)
Node=3, Range=(-∞, 5)
Why: Left child must be less than 5
Step 3: Check left child of 3 which is 2 with range (-∞, 3)
Node=2, Range=(-∞, 3)
Why: Left child must be less than 3
Step 4: Check right child of 3 which is 4 with range (3, 5)
Node=4, Range=(3, 5)
Why: Right child must be greater than 3 and less than 5
Step 5: Check right child 7 of root 5 with range (5, +∞)
Node=7, Range=(5, +∞)
Why: Right child must be greater than 5
Step 6: Check right child of 7 which is 8 with range (7, +∞)
Node=8, Range=(7, +∞)
Why: Right child must be greater than 7
Result:
Tree is a valid BST because all nodes fit their allowed ranges
Annotated Code
DSA Typescript
class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
  }
}

function isValidBST(root: TreeNode | null): boolean {
  function helper(node: TreeNode | null, min: number, max: number): boolean {
    if (node === null) return true;
    if (node.val <= min || node.val >= max) return false;
    return helper(node.left, min, node.val) && helper(node.right, node.val, max);
  }
  return helper(root, -Infinity, Infinity);
}

// Driver code to test the example tree
const root = new TreeNode(5,
  new TreeNode(3, new TreeNode(2), new TreeNode(4)),
  new TreeNode(7, null, new TreeNode(8))
);
console.log(isValidBST(root) ? "Tree is a valid BST" : "Tree is NOT a valid BST");
if (node === null) return true;
Base case: empty node means no violation
if (node.val <= min || node.val >= max) return false;
Check if current node violates BST range rules
return helper(node.left, min, node.val) && helper(node.right, node.val, max);
Recursively check left subtree with updated max and right subtree with updated min
OutputSuccess
Tree is a valid BST
Complexity Analysis
Time: O(n) because we visit each node once to check BST property
Space: O(h) where h is tree height due to recursion stack
vs Alternative: Compared to inorder traversal checking sorted order, this method checks BST property directly with ranges, avoiding extra storage
Edge Cases
Empty tree (root is null)
Returns true because empty tree is a valid BST
DSA Typescript
if (node === null) return true;
Single node tree
Returns true because one node always satisfies BST rules
DSA Typescript
if (node === null) return true;
Tree with duplicate values
Returns false because BST requires strictly less or greater values
DSA Typescript
if (node.val <= min || node.val >= max) return false;
When to Use This Pattern
When you need to check if a binary tree follows the BST rules, use range limits on nodes during recursion to verify each node fits the BST property.
Common Mistakes
Mistake: Only checking immediate children instead of all descendants for BST property
Fix: Use min and max range parameters to ensure all descendants fit BST rules, not just direct children
Mistake: Allowing equal values on left or right subtree
Fix: Use strict inequality (node.val <= min or node.val >= max) to disallow duplicates
Summary
Checks if a binary tree is a valid binary search tree by verifying node value ranges.
Use when you want to confirm a tree maintains BST ordering rules.
The key insight is to track allowed min and max values for each node during recursion.

Practice

(1/5)
1. What does it mean for a binary tree to be a Binary Search Tree (BST)?
easy
A. Every node has exactly two children
B. The tree is balanced with equal height on both sides
C. All nodes have the same value
D. Every node's left subtree has smaller values and right subtree has larger values

Solution

  1. Step 1: Understand BST property

    A BST requires that for each node, all values in the left subtree are smaller and all values in the right subtree are larger.
  2. Step 2: Compare options with definition

    Every node's left subtree has smaller values and right subtree has larger values matches the BST property exactly, while others describe different tree properties.
  3. Final Answer:

    Every node's left subtree has smaller values and right subtree has larger values -> Option D
  4. Quick Check:

    BST property = Every node's left subtree has smaller values and right subtree has larger values [OK]
Hint: Remember BST means left < node < right for all nodes [OK]
Common Mistakes:
  • Confusing BST with balanced tree
  • Thinking all nodes must have two children
  • Assuming all values are equal
2. Which TypeScript function signature correctly represents a function to check if a binary tree is a BST?
easy
A. function isBST(root: any): void
B. function isBST(root: TreeNode | null): boolean
C. function isBST(root: TreeNode): number
D. function isBST(root: number): boolean

Solution

  1. Step 1: Identify correct parameter and return types

    The function should accept a tree node or null and return a boolean indicating if it is a BST.
  2. Step 2: Match options with correct signature

    function isBST(root: TreeNode | null): boolean matches this: input is TreeNode or null, output is boolean. Others have wrong types or return types.
  3. Final Answer:

    function isBST(root: TreeNode | null): boolean -> Option B
  4. Quick Check:

    Correct signature = function isBST(root: TreeNode | null): boolean [OK]
Hint: Input is root node or null, output is true/false [OK]
Common Mistakes:
  • Using wrong parameter type like number
  • Returning number instead of boolean
  • Using void return type
3. What will be the output of the following TypeScript code snippet?
class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val: number, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function isBST(root: TreeNode | null, min: number = -Infinity, max: number = Infinity): boolean {
  if (!root) return true;
  if (root.val <= min || root.val >= max) return false;
  return isBST(root.left, min, root.val) && isBST(root.right, root.val, max);
}

const tree = new TreeNode(10, new TreeNode(5), new TreeNode(15, new TreeNode(6), new TreeNode(20)));
console.log(isBST(tree));
medium
A. SyntaxError
B. true
C. false
D. RuntimeError

Solution

  1. Step 1: Analyze the tree structure

    The root is 10, left child 5 (valid), right child 15 with left child 6 and right child 20.
  2. Step 2: Check BST property on right subtree

    Node 6 is in right subtree of 10 but less than 10, violating BST property. So function returns false.
  3. Final Answer:

    false -> Option C
  4. Quick Check:

    6 in right subtree < 10 = false [OK]
Hint: Check if left < node < right recursively [OK]
Common Mistakes:
  • Ignoring min/max constraints in recursion
  • Assuming all subtrees are BST without checks
  • Confusing node values in subtrees
4. Identify the bug in this TypeScript function to check if a tree is BST:
function isBST(root: TreeNode | null): boolean {
  if (!root) return true;
  if (root.left && root.left.val > root.val) return false;
  if (root.right && root.right.val < root.val) return false;
  return isBST(root.left) && isBST(root.right);
}
medium
A. It does not check the entire subtree values against min/max limits
B. It uses wrong comparison operators for left and right children
C. It returns true for null nodes incorrectly
D. It does not handle empty tree input

Solution

  1. Step 1: Understand the function checks

    The function only compares immediate children values with current node, not entire subtree ranges.
  2. Step 2: Explain why this is a bug

    BST requires all nodes in left subtree < current node and all in right subtree > current node, not just direct children.
  3. Final Answer:

    It does not check the entire subtree values against min/max limits -> Option A
  4. Quick Check:

    Missing min/max range check = It does not check the entire subtree values against min/max limits [OK]
Hint: Check full subtree ranges, not just immediate children [OK]
Common Mistakes:
  • Only comparing direct children values
  • Ignoring recursive min/max constraints
  • Assuming null nodes cause errors
5. Given a binary tree where nodes can have duplicate values, which modification to the BST validation logic allows duplicates only on the right subtree? Choose the correct condition to replace root.val <= min in the validation function:
function isBST(root: TreeNode | null, min: number = -Infinity, max: number = Infinity): boolean {
  if (!root) return true;
  if (root.val <= min || root.val >= max) return false;
  return isBST(root.left, min, root.val) && isBST(root.right, root.val, max);
}
hard
A. Change to root.val < min to allow duplicates on right
B. Change to root.val <= min and root.val < max
C. Change to root.val < min and root.val <= max
D. Change to root.val <= min and root.val <= max

Solution

  1. Step 1: Understand duplicates on right subtree rule

    Duplicates allowed only on right means left subtree nodes must be strictly less than current node, right subtree nodes greater than or equal.
  2. Step 2: Adjust min/max comparisons accordingly

    Replace root.val <= min with root.val < min. This fails only if strictly less than min (allows equal to min on right recursion), keeping root.val >= max for strict upper bound.
  3. Final Answer:

    Change to root.val < min to allow duplicates on right -> Option A
  4. Quick Check:

    Duplicates right subtree = Change to root.val < min [OK]
Hint: Use strict less on left, less or equal on right for duplicates [OK]
Common Mistakes:
  • Allowing duplicates on left subtree
  • Using <= on both sides
  • Not changing min/max checks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard