2Brute2Best
🔥0
04

BST properties (Tree DFS Sub-pattern)

Use the BST order: left < node < right. Search one side, read values in sorted order with inorder, or pass a valid range down.

Signals in the problem statement
  • ›

    "binary search tree" in the statement

  • ›

    "kth smallest" in a BST

  • ›

    "validate", "search", "delete" a key in a BST

What makes it different

Search walks down one side: O(h). Validate must pass a range from all ancestors; comparing a node with its children alone misses a small value deep in the right subtree. Kth Smallest is inorder that stops after k nodes. Delete has three cases: no child, one child (return it), two children (replace with the inorder successor, the leftmost node of the right subtree, then delete that successor).

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Search in a Binary Search Tree
    Basic Anchor·LeetCode #700
    Easy
  2. 2
    Validate Binary Search Tree
    Basic Reinforcement·LeetCode #98
    Medium
  3. 3
    Kth Smallest Element in a BST
    Slight Variation·LeetCode #230
    Medium
  4. 4
    Delete Node in a BST
    Medium·LeetCode #450
    Medium

Template

bst-range-template.cpp
// BST: every node must fit inside the (low, high) range set by its ancestors.
// long long bounds so a node equal to INT_MIN or INT_MAX still fits.
bool valid(TreeNode* node, long long low, long long high) {
    if (!node) return true;
    if (node->val <= low || node->val >= high) return false;
    return valid(node->left, low, node->val)             // left side: everything below node->val
        && valid(node->right, node->val, high);          // right side: everything above node->val
}

bool isValidBST(TreeNode* root) { return valid(root, LLONG_MIN, LLONG_MAX); }

// Searching only needs one side: the comparison tells you where the value must be.
TreeNode* searchBST(TreeNode* root, int target) {
    while (root && root->val != target)
        root = target < root->val ? root->left : root->right;
    return root;
}
Remember this · Tree DFS
Trigger
Paths, heights, diameters, validating structure, ancestors, anything "for every subtree".
Think
If my left and right children already gave me their answers, how do I build mine?
Key question
What does my recursive function return, and what do I pass down?