VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-the-number-of-nodes-in-a-binary-tree-in-constant-space/

⇱ Count the number of Nodes in a Binary Tree in Constant Space - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count the number of Nodes in a Binary Tree in Constant Space

Last Updated : 23 Jul, 2025

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:

👁 Binary-Tree


Output: 5
Explanation: In the above binary tree, there are total 5 nodes: 1, 2, 3, 4 and 5

Input:

👁 Binary-Tree-2


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:

  • Start by initializing two variables, cnt as 0 to keep track of the number of nodes counted and current as root to traverse the array.
  • Repeat the following steps until we have traversed the tree:
    • If the current node does not have a left child increase the count. Move to its right child.
    • If the current node has a left child find its inorder predecessor (the rightmost node, in its subtree).
    • If the predecessors right child is null set it to be the node and move to its child.
    • If the predecessors right child is already set as the node (indicating that we have visited its subtree) reset it to null increment the count and move to its right child.
  • Finally return the count variable which will contain the number of nodes in this tree.

Below is the implementation for the above approach:


Output
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)

Comment