Given a binary tree, check if each node has exactly one child or not. In other words, check whether the binary tree is skewed or not.

For example, the following binary tree is also skewed:

Skewed BST

Practice this problem

The idea is simple. If the binary tree’s height is equal to the total number of nodes in the tree, then the binary tree is skewed. Otherwise, the binary tree cannot be skewed. Following is the implementation in C++, Java, and Python based on the idea:

C++


Download  Run Code

Output:

The binary tree is skewed

Java


Download  Run Code

Output:

The binary tree is skewed

Python


Download  Run Code

Output:

The binary tree is skewed

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. However, it does two traversals of the binary tree – one to calculate its size and another to calculate its height. We can improve the above solution by calculating the height and the size in a single traversal tree, as demonstrated below.

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Another solution is to traverse the tree in a preorder fashion and check the total number of children for each node. If both the left child and the right child exists for a node, the binary tree cannot be skewed. Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

The binary tree is skewed

Java


Download  Run Code

Output:

The binary tree is skewed

Python


Download  Run Code

Output:

The binary tree is skewed

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(h) for the call stack, where h is the height of the tree.

 
Exercise: Modify the solution to check for left skewed binary tree or right skewed binary tree.