Table of contents
1.
Introduction
1.1.
Problem Statement
1.2.
Dry Run
2.
Approaches
2.1.
Approach 1
2.2.
Approach 2
2.3.
Approach 3
3.
Complexity Analysis 
3.1.
Time Complexity
3.2.
Space Complexity
4.
Frequently Asked Questions
4.1.
What is BST used for?
4.2.
What is an internal node?
4.3.
What is sizeof() in C++?
4.4.
Does sizeof work on arrays?
4.5.
Differentiate between an internal and external node in a binary tree?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

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

Author Amit Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Have you ever heard about the Binary Search Trees? Do you want to know how you can check if each internal node has exactly one child?

If yes, then your search for the solution is now over.

This article will help you in writing a program to check if each of the internal nodes of a BST has exactly one child.  

img1

Problem Statement

The problem statement is that we are given a preorder traversal of a Binary Search Tree. Using that information, we have to check if each of the non-leaf or internal nodes has only one child or not. Also, we will assume that all the entries present in the Binary Search Tree are unique.

 

Sample Input 1

{19, 9, 10, 12, 11}

 

Sample Output:

Yes

Dry Run

Preorder traversal places each node's descendants (or Preorder successors) behind the node.

img2

In the example mentioned above, node 19 is the first node in preorder, and all of its descendants follow it. 

All of the children of 19 are smaller than it. 

img3

Every descendant of 9 is greater than it. 

img4

In a BST or Binary Search Tree, we can claim that all descendants of an internal node are either smaller or larger than the node if all internal nodes have just one child. 

Simply said, because the tree is a BST or Binary Search Tree and each node has only one child, all of a node's descendants will either be on the left or right side, i.e., smaller or larger.

Approaches

Approach 1

Simply put, this strategy adheres to the presumption that all values on the right side are either smaller or greater. Use two loops; the outer loop selects each element one at a time, beginning with the element on the left. The inner loop determines if every element to the right of the selected element is smaller or larger. 

This approach has an O(n2) time complexity.

Approach 2

Given that every node's descendants must either be bigger or smaller than the node, For each node in a loop, we can perform the following.
 

  1. Locate the node's subsequent preorder successor (or descendant).
     
  2. Locate the node's last preorder successor (last element in prebst[]).
     
  3. Continue if both successors are less than the current node or both successors are greater than the current node. Return false if not.
     

Implementation in C++:

#include<bits/stdc++.h>
using namespace std;

/* function to check if the internal node of BST has exactly one child */

bool hasOnlyOneChild(int prebst[], int sizebst)
{
	int nextDiffer, lastDiffer;

	for (int i=0; i<sizebst-1; i++)
	{
		nextDiffer = prebst[i] - prebst[i+1];
		lastDiffer = prebst[i] - prebst[sizebst-1];
		if (nextDiffer*lastDiffer < 0)
			return false;;
	}
	return true;
}

int main()
{
	int sizebst;
	cout << "Enter the number of nodes you want in the tree: ";
	cin >> sizebst;
	
	int prebst[sizebst];
	cout << "Enter the nodes of the tree: ";

	for(int i=0; i<sizebst; i++) {
		cin >> prebst[i];
}

	if (hasOnlyOneChild(prebst, sizebst) == true )
		cout<<"Yes...";
	else
		cout<<"No!";
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

output

 

Implementation in Java

import java.util.*;


class CodingNinjas {
  
    boolean hasOnlyOneChild(int prebst[], int sizebst) {
        int nextDiffer, lastDiffer;
  
        for (int i = 0; i < sizebst - 1; i++) {
            nextDiffer = prebst[i] - prebst[i + 1];
            lastDiffer = prebst[i] - prebst[sizebst - 1];
            if (nextDiffer * lastDiffer < 0) {
                return false;
            };
        }
        return true;
    }
  
    public static void main(String[] args) {
        CodingNinjas bsttree = new CodingNinjas();
        int sizebst;
        Scanner scn = new Scanner(System.in);
        System.out.print("Enter the number of nodes you want in the tree: ");
        sizebst = scn.nextInt();
        
        int prebst[] = new int[sizebst];
        System.out.print("Enter the nodes of the tree: ");


        for(int i=0; i<sizebst; i++) {
            prebst[i] = scn.nextInt();
        }
        
        if (bsttree.hasOnlyOneChild(prebst, sizebst) == true) {
            System.out.println("Yes...");
        } else {
            System.out.println("No!");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

output

 

Implementation in Python:

def hasOnlyOneChild (prebst, sizebst):
    nextDiffer=0; lastDiffer=0
   
    for i in range(sizebst-1):
        nextDiffer = prebst[i] - prebst[i+1]
        lastDiffer = prebst[i] - prebst[sizebst-1]
        if nextDiffer*lastDiffer < 0:
            return False
    return True
   
if __name__ == "__main__":
  
    prebst = []
    n = int(input("Enter the number of nodes you want in the tree: "))
    print("Enter the nodes of the tree: ",end="")
    for i in range(0, n):
        ele = int(input())
        prebst.append(ele)
    sizebst= len(prebst)
  
    if (hasOnlyOneChild(prebst,sizebst) == True):
        print("Yes...")
    else:
        print("No!")
You can also try this code with Online Python Compiler
Run Code

 

Output:

output

Approach 3

  1. Scan the final two preorder nodes and mark them as minimum and maximum.
     
  2. Go through each node in the preorder array. Each node must be either smaller than the min node or greater than the max node. Update the minimum and maximum values appropriately.
     

Implementation in C++:

#include <bits/stdc++.h>
using namespace std;

/* Function to check if the internal node of BST has exactly one child */
int hasOnlyOneChild(int prebst[], int sizebst)
{	
	/* initialization of maximum and minimum */
	int minimum, maximum;
	if (prebst[sizebst - 1] > prebst[sizebst - 2])
	{
		maximum = prebst[sizebst - 1];
		minimum = prebst[sizebst - 2];
	}
	else
	{
		maximum = prebst[sizebst - 2];
		minimum = prebst[sizebst - 1];
	}

	/* Each element must be either smaller than the minimum 
    or greater than the maximum */
	   
	for(int i = sizebst - 3; i >= 0; i--)
	{
		if (prebst[i] < minimum)
			minimum = prebst[i];
		else if (prebst[i] > maximum)
			maximum = prebst[i];
		else
			return false;
	}
	return true;
}

int main()
{
	int sizebst;
	cout << "Enter the number of nodes you want in the tree: ";
	cin >> sizebst;
	
	int prebst[sizebst];
	cout << "Enter the nodes of the tree: ";

for(int i=0; i<sizebst; i++) {
cin >> prebst[i];
}

	if (hasOnlyOneChild(prebst,sizebst))
		cout <<"Yes...";
	else
		cout <<"No!";
		
	return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

ouput002

 

Implementation in Java

import java.util.*;

class CodingNinjas {
  
    boolean hasOnlyOneChild(int prebst[], int sizebst) {
     
        int minimum, maximum;
        if (prebst[sizebst - 1] > prebst[sizebst - 2]) {
            maximum = prebst[sizebst - 1];
            minimum = prebst[sizebst - 2];
        } else {
            maximum = prebst[sizebst - 2];
            minimum = prebst[sizebst - 1];
        }
  
        /* Every element must be either smaller than minimum 
           or greater than maximum */
        for(int i = sizebst - 3; i >= 0; i--) {
            if (prebst[i] < minimum) {
                minimum = prebst[i];
            } else if (prebst[i] > maximum) {
                maximum = prebst[i];
            } else {
                return false;
            }
        }
        return true;
    }
  
    public static void main(String[] args) {
        CodingNinjas bsttree = new CodingNinjas();
        int sizebst;
        Scanner scn = new Scanner(System.in);
        sizebst = scn.nextInt();
        
        int prebst[] = new int[sizebst];
        
        for(int i=0; i<sizebst; i++) {
            prebst[i] = scn.nextInt();
        }
        
        if (bsttree.hasOnlyOneChild(prebst, sizebst) == true) {
            System.out.println("Yes...");
        } else {
            System.out.println("No!");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

output003

 

Implementation in Python

def hasOnlyOneChild(prebst,sizebst):

	minimum=0; maximum=0

	if prebst[sizebst-1] > prebst[sizebst-2] :
		maximum = prebst[sizebst-1]
		minimum = prebst[sizebst-2]
	else :
		maximum = prebst[sizebst-2]
		minimum = prebst[sizebst-1]

	for i in range(sizebst-3, 0, -1):
		if prebst[i] < minimum:
			minimum = prebst[i]
		elif prebst[i] > maximum:
			maximum = prebst[i]
		else:
			return False
	return True

if __name__ == "__main__":
    prebst = []
    sizebst = int(input("Enter the number of nodes you want in the tree: "))
    print("Enter the nodes of the tree: ")
    for i in range(0, sizebst):
        ele = int(input())
        prebst.append(ele)
      
    if (hasOnlyOneChild(prebst,sizebst) == True):
        print("Yes...")
    else:
        print("No!")
You can also try this code with Online Python Compiler
Run Code

 

Output:

ouput004

 

Complexity Analysis 

Time Complexity

O(N), where ‘N’ is the number of nodes in the tree.

Since we are traversing the entire tree only once and at every traversal. 

Thus the time complexity is O(N).

Space Complexity

O(N), where 'N' is the number of nodes in the tree.

Since we are using an array, which will take O(N) space.

Check out this problem - Reverse Nodes In K Group

Frequently Asked Questions

What is BST used for?

A binary search tree (BST) is a data structure that provides a quick method for iterating through the items in sorted order while also enabling quick insertion, removal, and lookup of things.

What is an internal node?

An internal node is a node in a tree that has one or more child nodes or, alternatively, a node that is not a leaf. We can also call it a nonterminal node.

What is sizeof() in C++?

The sizeof() operator in C++ is used to determine the size of a specified data type, variable, or constant.

Does sizeof work on arrays?

Only fixed-size arrays can be used with sizeof() (which can be static, stack-based, or in a struct). You will always obtain the size of a pointer if you apply it to an array made with malloc (or new in C++).

Differentiate between an internal and external node in a binary tree?

A node that is internal has at least one child branch, whereas a node that is external has none.

Conclusion

In this article, we have studied how to write a program to check if each internal node of a BST has exactly one child. We hope that this article has provided you with the help to enhance your knowledge regarding hashmap and if you would like to learn more, check out our articles on Advantages of bst over hash tableReverse a path in bst using queue, and Minimum distance between bst nodes.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available, Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Merry Learning!

Live masterclass