Anuj Varma Software • Cloud • Security • AI

Binary tree (count nodes) interview question

Given a LEFT and a RIGHT property that returns the underlying LEFT tree and the underlying RIGHT tree respectively, find the total count of the nodes in the tree.
class BinaryTree<T>
{
private BinaryTree<T> left;
private BinaryTree<T> right;
public int CountNodes<T>(this IBinaryTree<T> tree)
    {
        // TODO: What goes here?
     }    
}
Solution
public int CountNodes<T>(this IBinaryTree<T> t) 
 {
   return  1 +  t.left.CountNodes() + t.right.CountNodes();
 }
 
      

Anuj holds professional certifications in Google Cloud, AWS as well as certifications in Docker and App Performance Tools such as New Relic. He specializes in Cloud Security, Data Encryption and Container Technologies.

Initial Consultation

Anuj Varma – who has written posts on Anuj Varma.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.