Given Preorder traversal of a BST, check if each non-leaf node has only one child. Assume that the BST contains unique entries.
Examples :
Input: pre[] = {20, 10, 11, 13, 12}
Output: Yes
The given array represents following BST. In the following BST, every internal
node has exactly 1 child. Therefore, the output is true.
20
/
10
\
11
\
13
/
12
In Preorder traversal, descendants (or Preorder successors) of every node appear after the node. In the above example, 20 is the first node in preorder and all descendants of 20 appear after it. All descendants of 20 are smaller than it. For 10, all descendants are greater than it. In general, we can say, if all internal nodes have only one child in a BST, then all the descendants of every node are either smaller or larger than the node. The reason is simple, since the tree is BST and every node has only one child, all descendants of a node will either be on left side or right side, means all descendants will either be smaller or greater.
Approach 1 (Naive): This approach simply follows the above idea that all values on right side are either smaller or larger. Use two loops, the outer loop picks an element one by one, starting from the leftmost element. The inner loop checks if all elements on the right side of the picked element are either smaller or greater. The time complexity of this method will be O(n^2).
Approach 2: Since all the descendants of a node must either be larger or smaller than the node. We can do following for every node in a loop.
Find the next preorder successor (or descendant) of the node.
Find the last preorder successor (last element in pre[]) of the node.
If both successors are less than the current node, or both successors are greater than the current node, then continue. Else, return false.
C++
#include<bits/stdc++.h>
usingnamespacestd;
boolhasOnlyOneChild(intpre[], intsize)
{
intnextDiff, lastDiff;
for(inti=0; i<size-1; i++)
{
nextDiff = pre[i] - pre[i+1];
lastDiff = pre[i] - pre[size-1];
if(nextDiff*lastDiff < 0)
returnfalse;;
}
returntrue;
}
// driver program to test above function
intmain()
{
intpre[] = {8, 3, 5, 7, 6};
intsize = sizeof(pre)/sizeof(pre[0]);
if(hasOnlyOneChild(pre, size) == true)
cout<<"Yes";
else
cout<<"No";
return0;
}
// This code is contributed by rrrtnx.
C
#include <stdio.h>
boolhasOnlyOneChild(intpre[], intsize)
{
intnextDiff, lastDiff;
for(inti=0; i<size-1; i++)
{
nextDiff = pre[i] - pre[i+1];
lastDiff = pre[i] - pre[size-1];
if(nextDiff*lastDiff < 0)
returnfalse;;
}
returntrue;
}
// driver program to test above function
intmain()
{
intpre[] = {8, 3, 5, 7, 6};
intsize = sizeof(pre)/sizeof(pre[0]);
if(hasOnlyOneChild(pre, size) == true)
printf("Yes");
else
printf("No");
return0;
}
Java
// Check if each internal node of BST has only one child
classBinaryTree {
booleanhasOnlyOneChild(intpre[], intsize) {
intnextDiff, lastDiff;
for(inti = 0; i < size - 1; i++) {
nextDiff = pre[i] - pre[i + 1];
lastDiff = pre[i] - pre[size - 1];
if(nextDiff * lastDiff < 0) {
returnfalse;
};
}
returntrue;
}
publicstaticvoidmain(String[] args) {
BinaryTree tree = newBinaryTree();
intpre[] = newint[]{8, 3, 5, 7, 6};
intsize = pre.length;
if(tree.hasOnlyOneChild(pre, size) == true) {
System.out.println("Yes");
} else{
System.out.println("No");
}
}
}
// This code has been contributed by Mayank Jaiswal
Python3
# Check if each internal
# node of BST has only one child
defhasOnlyOneChild (pre, size):
nextDiff=0; lastDiff=0
fori inrange(size-1):
nextDiff =pre[i] -pre[i+1]
lastDiff =pre[i] -pre[size-1]
ifnextDiff*lastDiff < 0:
returnFalse
returnTrue
# driver program to
# test above function
if__name__ =="__main__":
pre =[8, 3, 5, 7, 6]
size=len(pre)
if(hasOnlyOneChild(pre,size) ==True):
print("Yes")
else:
print("No")
# This code is contributed by
# Harshit Saini
C#
// Check if each internal node of BST has only one child
usingSystem;
publicclassBinaryTree
{
boolhasOnlyOneChild(int[] pre, intsize)
{
intnextDiff, lastDiff;
for(inti = 0; i < size - 1; i++)
{
nextDiff = pre[i] - pre[i + 1];
lastDiff = pre[i] - pre[size - 1];
if(nextDiff * lastDiff < 0)
{
returnfalse;
};
}
returntrue;
}
// Driver code
publicstaticvoidMain(String[] args)
{
BinaryTree tree = newBinaryTree();
int[]pre = newint[]{8, 3, 5, 7, 6};
intsize = pre.Length;
if(tree.hasOnlyOneChild(pre, size) == true)
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
// This code is contributed by aashish1995
Javascript
<script>
// Check if each internal node of BST has only one child
functionhasOnlyOneChild(pre, size)
{
varnextDiff, lastDiff;
for(vari = 0; i < size - 1; i++)
{
nextDiff = pre[i] - pre[i + 1];
lastDiff = pre[i] - pre[size - 1];
if(nextDiff * lastDiff < 0)
{
returnfalse;
};
}
returntrue;
}
// Driver code
varpre = [8, 3, 5, 7, 6];
varsize = pre.length;
if(hasOnlyOneChild(pre, size) == true)
{
document.write("Yes");
}
else
{
document.write("No");
}
// This code is contributed by itsok.
</script>
Output
Yes
Approach 3 :
Scan the last two nodes of preorder & mark them as min & max.
Scan every node down the preorder array. Each node must be either smaller than the min node or larger than the max node. Update min & max accordingly.
C++
#include <bits/stdc++.h>
usingnamespacestd;
inthasOnlyOneChild(intpre[], intsize)
{
// Initialize min and max using last two elements
intmin, max;
if(pre[size - 1] > pre[size - 2])
{
max = pre[size - 1];
min = pre[size - 2];
}
else
{
max = pre[size - 2];
min = pre[size - 1];
}
// Every element must be either smaller
// than min or greater than max
for(inti = size - 3; i >= 0; i--)
{
if(pre[i] < min)
min = pre[i];
elseif(pre[i] > max)
max = pre[i];
else
returnfalse;
}
returntrue;
}
// Driver code
intmain()
{
intpre[] = { 8, 3, 5, 7, 6 };
intsize = sizeof(pre) / sizeof(pre[0]);
if(hasOnlyOneChild(pre,size))
cout <<"Yes";
else
cout <<"No";
return0;
}
// This code is contributed by shivanisinghss2110
C
#include <stdio.h>
inthasOnlyOneChild(intpre[], intsize)
{
// Initialize min and max using last two elements
intmin, max;
if(pre[size-1] > pre[size-2])
{
max = pre[size-1];
min = pre[size-2];
}
else
{
max = pre[size-2];
min = pre[size-1];
}
// Every element must be either smaller than min or
// greater than max
for(inti=size-3; i>=0; i--)
{
if(pre[i] < min)
min = pre[i];
elseif(pre[i] > max)
max = pre[i];
else
returnfalse;
}
returntrue;
}
// Driver program to test above function
intmain()
{
intpre[] = {8, 3, 5, 7, 6};
intsize = sizeof(pre)/sizeof(pre[0]);
if(hasOnlyOneChild(pre,size))
printf("Yes");
else
printf("No");
return0;
}
Java
// Check if each internal node of BST has only one child
classBinaryTree {
booleanhasOnlyOneChild(intpre[], intsize) {
// Initialize min and max using last two elements
intmin, max;
if(pre[size - 1] > pre[size - 2]) {
max = pre[size - 1];
min = pre[size - 2];
} else{
max = pre[size - 2];
min = pre[size - 1];
}
// Every element must be either smaller than min or
// greater than max
for(inti = size - 3; i >= 0; i--) {
if(pre[i] < min) {
min = pre[i];
} elseif(pre[i] > max) {
max = pre[i];
} else{
returnfalse;
}
}
returntrue;
}
publicstaticvoidmain(String[] args) {
BinaryTree tree = newBinaryTree();
intpre[] = newint[]{8, 3, 5, 7, 6};
intsize = pre.length;
if(tree.hasOnlyOneChild(pre, size) == true) {
System.out.println("Yes");
} else{
System.out.println("No");
}
}
}
// This code has been contributed by Mayank Jaiswal
Python3
# Check if each internal
# node of BST has only one child
# approach 2
defhasOnlyOneChild(pre,size):
# Initialize min and max
# using last two elements
min=0; max=0
ifpre[size-1] > pre[size-2] :
max=pre[size-1]
min=pre[size-2]
else:
max=pre[size-2]
min=pre[size-1]
# Every element must be
# either smaller than min or
# greater than max
fori inrange(size-3, 0, -1):
ifpre[i] < min:
min=pre[i]
elifpre[i] > max:
max=pre[i]
else:
returnFalse
returnTrue
# Driver program to
# test above function
if__name__ =="__main__":
pre =[8, 3, 5, 7, 6]
size =len(pre)
if(hasOnlyOneChild(pre, size)):
print("Yes")
else:
print("No")
# This code is contributed by
# Harshit Saini
C#
// Check if each internal node of BST has only one child
usingSystem;
publicclassBinaryTree
{
boolhasOnlyOneChild(int[]pre, intsize)
{
// Initialize min and max using last two elements
intmin, max;
if(pre[size - 1] > pre[size - 2]) {
max = pre[size - 1];
min = pre[size - 2];
} else{
max = pre[size - 2];
min = pre[size - 1];
}
// Every element must be either smaller than min or
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy