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:

Get hands-on with 1400+ tech skills courses.