How to calculate size of binary tree


This is a continuation of my post How to create a binary tree in c#.In this post, I will show you how to find the size of the binary tree.

Size of the binary tree is the number of nodes in a given tree.

Following is the recursive implementation of size function

  //Compute the number of nodes in a tree. 
        public int Size()
        {
            return Size(_root);
        }
        private int Size(Node root)
        {
            if (root == null)
                return 0;
            return 1 + Size(root.Left) + Size(root.Right);
        }

Reactions

Post a Comment

0 Comments

Close Menu