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)
- 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
- 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.
- Postorder traversal of Binary Tree without recursion and without stack
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- Calculate depth of a full Binary tree from Preorder
- Check if a Binary Tree contains duplicate subtrees of size 2 or more
- A program to check if a binary tree is BST or not
- Program to count leaf nodes in a binary tree