- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

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

# Check if each internal node of a BST has exactly one child in Python

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 −

## Example

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))

## Input

[22, 12, 13, 15, 14]

## Output

True

- Related Articles
- Check if a Binary Tree (not BST) has duplicate value in C++
- Check if a triplet with given sum exists in BST in Python
- Delete Node in a BST in C++
- How to check if a string has at least one letter and one number in Python?
- First and last child node of a specific node in JavaScript?
- Replace a child node with a new node in JavaScript?
- Python Pandas – Check if two Dataframes are exactly same
- Program to check whether one value is present in BST or not in Python
- Check if a string has all characters with same frequency with one variation allowed in Python
- Insert a node as a child before an existing child in JavaScript?
- Child node count in JavaScript?
- Check if a binary string has two consecutive occurrences of one everywhere in C++
- Can you draw a triangle which has(a) exactly one line of symmetry?(b) exactly two lines of symmetry?(c) exactly three lines of symmetry?(d) no lines of symmetry?Sketch a rough figure in each case.
- Remove the child node of a specific element in JavaScript?
- Remove all child elements of a DOM node in JavaScript?

Advertisements