Given a Binary search Tree that contains positive integer values greater then 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.
Input : 8 / \ 5 9 / \ 2 7 / 1 Output : Yes Explanation : Node "1" is the dead End because after that we cant insert any element. Input : 8 / \ 7 10 / / \ 2 9 13 Output : Yes Explanation : We can't insert any element at node 9.
If we take a closer look at problem, we can notice that we basically need to check if there is leaf node with value x such that x+1 and x-1 exist in BST with exception of x = 1. For x = 1, we can’t insert 0 as problem statement says BST contains positive integers only.
To implement above idea we first traverse whole BST and store all nodes in a hash_map. We also store all leaves in a separate hash to avoid re-traversal of BST. Finally we check for every leaf node x, if x-1 and x+1 are present in hash_map or not.
Below is C++ implementation of above idea .
Time Complexity : O(n)
This article is contributed by Nishant_Singh(Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Simple Recursive solution to check whether BST contains dead end
- K'th Largest Element in BST when modification to BST is not allowed
- Check if the Binary Tree contains a balanced BST of size K
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST | Set-2
- Two nodes of a BST are swapped, correct the BST
- Find k-th smallest element in BST (Order Statistics in BST)
- A program to check if a binary tree is BST or not
- Check if a Binary Tree (not BST) has duplicate values
- Check given array of size n can represent BST of n levels or not
- Check if a String contains Anagrams of length K which does not contain the character X
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Check whether a binary tree is a full binary tree or not
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Check whether a given binary tree is perfect or not
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Check whether the two Binary Search Trees are Identical or Not
- Check whether a given binary tree is skewed binary tree or not?
- Check whether a node is leaf node or not for multiple queries
- C++ program to check whether a String is a Pangram or not