- 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++
- First and last child node of a specific node in JavaScript?
- Delete Node in a BST in C++
- Check if a string has all characters with same frequency with one variation allowed in Python
- Check if a triplet with given sum exists in BST in Python
- Replace a child node with a new node in JavaScript?
- Child node count in JavaScript?
- Insert a node as a child before an existing child in JavaScript?
- Check if one list is subset of other in Python
- Remove the child node of a specific element in JavaScript?
- Remove all child elements of a DOM node in JavaScript?
- Check if a string has m consecutive 1s or 0s in Python
- Check if all rows of a matrix are circular rotations of each other in Python

- 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

Advertisements