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)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Iterative program to Calculate Size of a tree
- Write a program to Delete a Tree
- Write a Program to Find the Maximum Depth or Height of a Tree
- DFS traversal of a tree using recursion
- Zig-Zag traversal of a Binary Tree using Recursion
- Preorder Traversal of N-ary Tree Without Recursion
- Inorder Tree Traversal without Recursion
- Inorder Tree Traversal without recursion and without stack!
- The Great Tree-List Recursion Problem.
- Bottom View of a Binary Tree using Recursion
- Postorder traversal of Binary Tree without recursion and without stack
- Find Maximum Level Sum in Binary Tree using Recursion
- Calculate depth of a full Binary tree from Preorder
- Find the node with maximum value in a Binary Search Tree using recursion
- Find the node with minimum value in a Binary Search Tree using recursion
- Product of nodes at k-th level in a tree represented as string using Recursion
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Find maximum and minimum element in binary tree without using recursion or stack or queue