Size of a tree is the number of elements present in the tree. Size of the below tree is 5.
Size() function recursively calculates the size of a tree. It works as follows:
Size of a tree = Size of left subtree + 1 + Size of right subtree.
size(tree) 1. If tree is empty then return 0 2. Else (a) Get the size of left subtree recursively i.e., call size( tree->left-subtree) (a) Get the size of right subtree recursively i.e., call size( tree->right-subtree) (c) Calculate size of the tree as following: tree_size = size(left-subtree) + size(right- subtree) + 1 (d) Return tree_size
Size of the tree is 5
Time & Space Complexities: Since this program is similar to traversal of tree, time and space complexities will be same as Tree traversal (Please see our Tree Traversal post for details)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Iterative program to Calculate Size of a tree
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Delete a Tree
- The Great Tree-List Recursion Problem.
- Inorder Tree Traversal without Recursion
- Inorder Tree Traversal without recursion and without stack!
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- DFS traversal of a tree using recursion
- Postorder traversal of Binary Tree without recursion and without stack
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Zig-Zag traversal of a Binary Tree using Recursion
- Find the node with minimum value in a Binary Search Tree using recursion
- Find the node with maximum value in a Binary Search Tree using recursion
- Find maximum and minimum element in binary tree without using recursion or stack or queue
- Find Maximum Level Sum in Binary Tree using Recursion
- Bottom View of a Binary Tree using Recursion
- Product of nodes at k-th level in a tree represented as string using Recursion
- Preorder Traversal of N-ary Tree Without Recursion
- Calculate depth of a full Binary tree from Preorder
- Calculate height of Binary Tree using Inorder and Level Order Traversal