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”- 1Search in a Binary Search TreeWalkthroughEasyBasic Anchor·LeetCode #700
- 2Validate Binary Search TreeWalkthroughMediumBasic Reinforcement·LeetCode #98
- 3Kth Smallest Element in a BSTWalkthroughMediumSlight Variation·LeetCode #230
- 4Delete Node in a BSTWalkthroughMediumMedium·LeetCode #450
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?