09. BST with Dead End
โ GFG solution to BST with Dead End: detect if a BST has any dead-end node where no more insertions are possible while maintaining BST properties. ๐
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
You are given a Binary Search Tree (BST) that contains only unique positive integers greater than 0. A dead end is a leaf node such that no further node can be inserted under it while still maintaining the BST property and constraint that node values must be > 0.
Your task is to determine whether the BST contains any such dead end.
๐ Examples
Example 1
Input: root[] = [8, 5, 9, 2, 7, N, N, 1]
Output: true
Explanation: Node 1 is a dead end since 0 is not allowed and 2 already exists.
Example 2
Input: root[] = [8, 7, 10, 2, N, 9, 13]
Output: true
Explanation: Node 9 is a dead end as no new node can be inserted below it.
๐ Constraints
$1 \leq \text{Number of nodes} \leq 3000$
$1 \leq \text{Node->data} \leq 10^5$
โ
My Approach
DFS with Dynamic Range [Low, High]
We recursively traverse the tree, carrying two bounds:
l: the lowest possible value a child node can taker: the highest possible value a child node can take
If we encounter a leaf node where l == r, it means:
There is no space left to insert any node under this leaf while obeying BST rules and positivity constraint.
๐ก Logic:
Initially call:
dfs(root, 1, INT_MAX)For each node:
Check left:
dfs(root->left, l, root->data - 1)Check right:
dfs(root->right, root->data + 1, r)
If
l == rat a leaf โ Dead End found.
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we visit each node exactly once.
Expected Auxiliary Space Complexity: O(h), where
his the height of the BST due to recursion stack.
๐งโ๐ป Code (C++)
๐งโ๐ป Code (Java)
๐ Code (Python)
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated