![]() |
VOOZH | about |
Given a Binary search Tree that contains positive integer values greater than 0. The task is to check whether the BST contains a dead end or not. Here Dead End means, we are not able to insert any element after that node.
Examples:
Input: root[] = [8, 5, 9, 2, 7, N, N, 1]
👁 Image
Output: true
Explanation: Node 1 is a Dead End in the given BST.Input: root[] = [8, 7, 10, 2, N, 9, 13]
👁 Image
Output: true
Explanation: Node 9 is a Dead End in the given BST.
Table of Content
Observation:
A dead end in a Binary Search Tree (BST) refers to a leaf node where no further insertions can be made without violating the properties of the BST. Since BSTs typically contain only positive integers greater than 0, a node becomes a dead end when both of its adjacent values that is, (value - 1) and (value + 1) — are already present in the tree. In such cases, no new node can be inserted in that position while maintaining the BST's structural rules.
Note: For value 0, we return true as this value cannot be added to the tree.
The idea is to iterate through each leaf node and check whether the values
value - 1andvalue + 1exist in the tree. If both of these values are present, it indicates a dead end, and the function returnstrue. This check is performed recursively while traversing the tree.
true
The idea is to store all node values in one set and only leaf node values in another set. Then, for each leaf node, we check if both its immediate predecessor and successor exist in the all-node set. If they do, then that leaf is a dead end because no other number can be inserted in that place in the BST.
Step by Step Implementation:
true
The idea is to store all node values in one set and then traverse the tree again to identify leaf nodes. For each leaf node, check if both (value - 1) and (value + 1) exist in the same set. If yes, it indicates a dead end.
true
The idea is to perform depth first search traversal on the tree, while maintaining the range of each subtree root. If for any leaf node, the size of range becomes 1 (this value is taken by leaf node already), it means no node can be inserted to this leaf node, and hence it is a dead end.
Step by step approach:
Illustration:
true