Challenge: Number of Elements

Let’s calculate the number of nodes in a tree using recursion.


Given a binary tree, find the total number of nodes in a binary tree.


The root of a binary tree.


Display the total number of nodes in a tree.

Sample input

The root node t.root of a binary tree will be our input, for which we have to calculate the number of elements using the numNodes() function.

Here’s the sample input tree t.

t := LevelOrderBinaryTree(arr)

Sample output


Let’s look at the illustration below to better understand the problem.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.