![]() |
VOOZH | about |
Given a binary tree having N nodes, count the number of nodes using constant O(1) space. This can be done by simple traversals like- Preorder, InOrder, PostOrder, and LevelOrder but these traversals require an extra space which is equal to the height of the tree.
Examples:
Input:
Output: 5
Explanation: In the above binary tree, there are total 5 nodes: 1, 2, 3, 4 and 5Input:
Output: 7
Explanation: In the above binary tree, there are total 7 nodes: 1, 2, 3, 4, 5, 6 and 7
Approach: To solve the problem follow the below idea:
We can solve this problem using the Morris Traversal—a Threaded Binary Tree traversal technique that enables us traverse all the nodes in any binary tree in constant space. Morris traversal does not rely on any additional data structure. The process operates by altering the arrangement of the tree as we navigate through it and subsequently restoring it back to the original state.
Steps to count nodes in a tree using Morris Traversal:
Below is the implementation for the above approach:
Number of nodes in the binary tree: 5
Time Complexity: O(N), where N is the number of nodes in the binary tree
Auxiliary Space: O(1)