Challenge: Number of Elements

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

Problem

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

Input

The root of a binary tree.

Output

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

10

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

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