Solution Review: Number of Elements

Let’s take a detailed look at the previous challenge’s solution.

Solution

We find the number of nodes (or all the elements) in a binary tree by summing the following

  • The number of nodes in the right subtree.
  • The number of nodes in the left subtree.
  • Adding 1 to the sum of the above.
Total nodes = (number of nodes in the right subtree) + 
              (number of nodes in the left subtree) + 1

We can code this solution as follows:

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