Check whether BST contains Dead end
Pattern: Validate BST
A BST of positive integers has a dead end if some leaf leaves no room for any new value below it: its value x has both x - 1 and x + 1 already present (or x is 1 and 2 is present). Pass down the range each node may take; a leaf whose range has shrunk to a single value is a dead end.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
The BST holds positive integers. Return whether it has a dead end: a leaf below which no new positive integer could
ever be inserted. The catalogue has no practice link for this one. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- What values may go under a leaf?
- When is there no such value?
- How do you know a leaf's allowed range?
Hints
Brute force, and why it fails
For each leaf, search the tree for its two neighbours: O(n h).
The key insight
The range passed down already encodes every ancestor, so a leaf is a dead end exactly when its range is one number.
Dry run
| range of 1 | [1, 1] |
|---|
BST [8, 5, 9, 2, 7, null, null, 1]. The leaf 1 has range [1, 1]: values below 2 and at least 1.
The plan
dead(n, lo, hi): if null: false
if leaf: return lo == hi
return dead(n.left, lo, n.val - 1) or dead(n.right, n.val + 1, hi)
start with [1, max int]
Complexity
- Time
O(n)- Space
O(h)
One pass.
Edge cases
- A leaf with value 1 next to 2.
- One node: not a dead end.
- Values far apart: no dead ends.
I've built my logic, show the code
Java
class Solution {
public boolean isDeadEnd(TreeNode root) {
return dead(root, 1, Integer.MAX_VALUE);
}
private boolean dead(TreeNode n, int lo, int hi) { // n's value must be in [lo, hi]
if (n == null) return false;
if (n.left == null && n.right == null) return lo == hi; // a leaf with no room left at all
return dead(n.left, lo, n.val - 1) || dead(n.right, n.val + 1, hi);
}
}C++
class Solution {
public:
bool isDeadEnd(TreeNode* root) {
return dead(root, 1, INT_MAX);
}
bool dead(TreeNode* n, int lo, int hi) { // n's value must be in [lo, hi]
if (n == NULL) return false;
if (n->left == NULL && n->right == NULL) return lo == hi; // a leaf with no room left at all
return dead(n->left, lo, n->val - 1) || dead(n->right, n->val + 1, hi);
}
};Python
class Solution:
def isDeadEnd(self, root) -> bool:
def dead(n, lo, hi) -> bool: # n's value must be in [lo, hi]
if n is None:
return False
if not n.left and not n.right:
return lo == hi # a leaf with no room left at all
return dead(n.left, lo, n.val - 1) or dead(n.right, n.val + 1, hi)
return dead(root, 1, 2**31 - 1)Common mistakes
- Forgetting that values must be positive (so 1 is the lowest).
- Checking only the parent.