- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have the preorder traversal of a binary search tree (BST). We have to check whether each internal node has only one child or not.

So, if the input is like preorder = [22, 12, 13, 15, 14], then the output will be True as BST is like −

To solve this, we can follow one efficient approach. As all decedents of a node is either smaller or larger, then we can we can follow these steps −

Get the next preorder successor of the node

Get the last preorder successor of the node

Now when both the successors are less than or greater than the current node then check again otherwise return false.

To solve this, we will follow these steps −

- next := 0, last := 0
- for i in range 0 to size of preorder - 1, do
- next := preorder[i] - preorder[i+1]
- last := preorder[i] - last value of preorder
- if next * last < 0, then
- return False

- return True

Let us see the following implementation to get better understanding −

def solve(preorder): next = 0 last = 0 for i in range(len(preorder)-1): next = preorder[i] - preorder[i+1] last = preorder[i] - preorder[-1] if next * last < 0: return False return True preorder = [22, 12, 13, 15, 14] print(solve(preorder))

[22, 12, 13, 15, 14]

True

- Related Questions & Answers
- Check if a Binary Tree (not BST) has duplicate value in C++
- How to check if a string has at least one letter and one number in Python?
- Check if a binary string has two consecutive occurrences of one everywhere in C++
- Check if a triplet with given sum exists in BST in Python
- Check if a string has all characters with same frequency with one variation allowed in Python
- First and last child node of a specific node in JavaScript?
- Delete Node in a BST in C++
- Replace a child node with a new node in JavaScript?
- Python Pandas – Check if two Dataframes are exactly same
- Check if tuple has any None value in Python
- Program to check if binary string has at most one segment of ones or not using Python
- Check if one list is subset of other in Python
- Check if one tuple is subset of other in Python
- Child node count in JavaScript?
- Insert a node as a child before an existing child in JavaScript?

Advertisements