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 firstname.lastname@example.org. 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
- Check if two trees are Mirror | Set 2
- Check if two Integer are anagrams of each other
- Check if two trees have same structure
- Check if given string contains all the digits
- Check if one string can be converted to another
- Check if two trees are Mirror
- Check if a string is Isogram or not
- Check if two BSTs contain same set of elements
- Check mirror in n-ary tree
- Check if two strings are k-anagrams or not
- Check if two arrays are permutations of each other
- Check if a given graph is tree or not
- Check if two arrays are equal or not
- Check if all leaves are at same level
- How to check if two given sets are disjoint?
- Check if a triplet with given sum exists in BST
- Check if two given key sequences construct same BSTs
- Check if all array elements are distinct
- Check whether the given node is in the path between the nodes U and V