Count Complete Tree Nodes
LeetCode Problem #222 (Medium)
Problem Statement
Given a complete binary tree, count the number of nodes.
Testcase
Prerequisite Knowledge
Complete Binary Tree
In a complete binary tree, every level must be completely filled. That is, every node starting from the root node must have exactly two children. The only exception to this rule is that the last level of the binary tree may be incomplete. However, the nodes in the last level must be filled from left to right. Therefore, the leaf nodes of the complete binary tree must always lean left.
In the image above, we can see that the binary tree has three levels.
The first level contains one node, which is is the root node, marked by the number 1
.
The root node has exactly two children which form the second level of the binary tree, marked by 2
and 3
respectively.
The third level contains only three elements instead of the maximum capacity of four. This is allowed in a complete binary tree as the third level contains the leaf nodes of the tree. However, we can see that the leaf nodes have been filled from left to right.
Node 2 has exactly two children, marked by 4
and 5
. Node 3 has only one child, marked by 6
.
Algorithm
Recursive Approach
If the tree is empty, return 0 as the number of nodes.
Recursively traverse through each branch of the complete binary tree and calculate the number of nodes in each branch.
Add 1 to the number of nodes found in the left and right branches to account for the root node and return this value as the total number of nodes in the complete binary tree.
Code
Last updated
Was this helpful?