Practice: BSTs
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Solving varied binary search tree challenges refines range trimming, structure recovery, and data structure choices.
Recovering swapped nodes and trimming a BST
Two problems: recover a BST in which two values were swapped, and trim a BST so every value stays inside [low, high]. Both rely on the BST ordering rule.
Example 1 · Trim a BST to Range
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static TreeNode trimBST(TreeNode root, int low, int high) { if (root == null) return null; if (root.val < low) return trimBST(root.right, low, high); if (root.val > high) return trimBST(root.left, low, high);
root.left = trimBST(root.left, low, high); root.right = trimBST(root.right, low, high); return root; }
static void inorder(TreeNode root) { if (root == null) return; inorder(root.left); System.out.print(root.val + " "); inorder(root.right); }
public static void main(String[] args) { TreeNode root = new TreeNode(3); root.left = new TreeNode(0); root.right = new TreeNode(4); root.left.right = new TreeNode(2); root.left.right.left = new TreeNode(1);
root = trimBST(root, 1, 3); inorder(root); System.out.println(); }}1 2 3
What this code does
- Nodes smaller than low are bypassed in favor of their right child subtrees.
- Nodes larger than high are bypassed in favor of their left child subtrees.
- The remaining nodes satisfy the closed range [1, 3].
Example 2 · Recover Swapped BST Nodes
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static TreeNode first = null; static TreeNode second = null; static TreeNode prev = null;
static void inorder(TreeNode node) { if (node == null) return; inorder(node.left); if (prev != null && node.val < prev.val) { if (first == null) first = prev; second = node; } prev = node; inorder(node.right); }
static void recoverTree(TreeNode root) { first = second = prev = null; inorder(root); if (first != null && second != null) { int temp = first.val; first.val = second.val; second.val = temp; } }
public static void main(String[] args) { TreeNode root = new TreeNode(3); root.left = new TreeNode(1); root.right = new TreeNode(4); root.right.left = new TreeNode(2);
recoverTree(root); System.out.println("Restored root: " + root.val); System.out.println("Restored right-left: " + root.right.left.val); }}Restored root: 2 Restored right-left: 3
What this code does
- Inorder traversal identifies nodes where the ascending sequence breaks.
- The first anomaly captures the larger misplaced node.
- Swapping values of first and second restores valid BST structure.
Two nodes in a binary search tree might be accidentally swapped, breaking the invariant. Because an inorder traversal should be sorted, two inversions indicate the swapped positions. Record the first inverted node and the last inverted node during traversal. Swapping their values restores the correct binary search tree in linear O(n) time.
Trimming a BST drops all nodes falling outside a specified [low, high] interval. If a node value is strictly less than low, discard it and its entire left subtree. Return the trimmed right child instead. If a node value is strictly greater than high, discard it and return the trimmed left child.
Finding the largest BST and converting to greater trees
Two more problems: turn a BST into a greater sum tree with a reverse inorder walk, and find the largest valid BST hiding inside a general tree.
Example 3 · Convert BST to Greater Sum Tree
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static int sum = 0;
static TreeNode bstToGst(TreeNode root) { sum = 0; traverse(root); return root; }
static void traverse(TreeNode node) { if (node == null) return; traverse(node.right); sum += node.val; node.val = sum; traverse(node.left); }
static void inorder(TreeNode root) { if (root == null) return; inorder(root.left); System.out.print(root.val + " "); inorder(root.right); }
public static void main(String[] args) { TreeNode root = new TreeNode(4); root.left = new TreeNode(1); root.right = new TreeNode(6);
bstToGst(root); inorder(root); System.out.println(); }}11 10 6
What this code does
- Reverse inorder visits keys in descending order: 6, then 4, then 1.
- A running accumulator adds each node value and updates the node.
- Original keys {1, 4, 6} transform into {11, 10, 6}.
A general binary tree may contain valid BST subtrees inside itself. We can find the largest BST subtree using bottom-up postorder traversal. Each subtree returns four metrics: whether it is a valid BST, its size, its minimum, and its maximum. If both children are valid BSTs and root sits between left max and right min, combine them.
Converting a BST to a greater tree replaces each key with the sum of all greater keys. Perform reverse inorder traversal (right, root, left) while accumulating a running sum. At each node, add the node value to the running sum and overwrite the node value.
Choosing between a BST and a hash map
A hash map answers exact key lookups in O(1) expected time.
A binary search tree, such as Java's TreeMap, keeps its keys sorted, so it also answers range and nearest-key questions.
import java.util.*;
public class MapChoice { public static void main(String[] args) { Map<String, Integer> marks = new HashMap<>(); // exact lookups only marks.put("Asha", 72); System.out.println(marks.get("Asha")); TreeMap<Integer, String> byScore = new TreeMap<>(); // keys kept sorted byScore.put(72, "Asha"); byScore.put(88, "Ravi"); byScore.put(95, "Meera"); System.out.println(byScore.floorKey(90)); // nearest score at or below 90 System.out.println(byScore.subMap(70, 90)); // range scan: scores 70 to 89 }}72
88
{72=Asha, 88=Ravi}Choose a hash map when you only require exact key lookups. Choose a binary search tree when you need sorted keys, range scans, or nearest neighbor lookups. BSTs guarantee O(log n) time without hash collisions or resizing latency spikes.
Finish up
Mark complete & continue
Next: What a heap is