222. Count Complete Tree Nodes
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to count the total number of nodes in a given complete binary tree. A standard tree traversal like DFS or BFS would visit every node, resulting in an O(n) time complexity. The problem statement explicitly asks for a solution with a time complexity better than O(n), which implies that we must leverage the special properties of a complete binary tree.
Solution
Count Complete Tree Nodes in Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
# Helper function to calculate the height of a tree by its leftmost path.
def get_height(node: Optional[TreeNode]) -> int:
height = 0
while node:
height += 1
node = node.left
return height
left_height = get_height(root.left)
right_height = get_height(root.right)
if left_height == right_height:
# If heights are equal, the left subtree is a perfect binary tree.
# The total number of nodes is 1 (root) + (2^left_height - 1) (left subtree)
# + nodes in the right subtree.
# This simplifies to (1 << left_height) + countNodes(root.right).
return (1 << left_height) + self.countNodes(root.right)
else:
# If left_height > right_height, the right subtree is a perfect binary tree.
# This is because in a complete tree, left_height can be at most right_height + 1.
# The total nodes are 1 (root) + nodes in left subtree + (2^right_height - 1) (right subtree).
# This simplifies to countNodes(root.left) + (1 << right_height).
return (1 << right_height) + self.countNodes(root.left)
Count Complete Tree Nodes in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
// Get the height of the left and right subtrees.
// Height is defined as the number of nodes on the leftmost path.
int leftHeight = getHeight(root.left);
int rightHeight = getHeight(root.right);
if (leftHeight == rightHeight) {
// If heights are equal, the left subtree is a perfect binary tree.
// The total number of nodes is 1 (root) + (2^leftHeight - 1) (left subtree)
// + nodes in the right subtree.
// This simplifies to (1 << leftHeight) + countNodes(root.right).
return (1 << leftHeight) + countNodes(root.right);
} else {
// If leftHeight > rightHeight, the right subtree is a perfect binary tree.
// This is because in a complete tree, leftHeight can be at most rightHeight + 1.
// The total nodes are 1 (root) + nodes in left subtree + (2^rightHeight - 1) (right subtree).
// This simplifies to countNodes(root.left) + (1 << rightHeight).
return (1 << rightHeight) + countNodes(root.left);
}
}
// Helper function to calculate the height of a tree by its leftmost path.
private int getHeight(TreeNode node) {
int height = 0;
while (node != null) {
height++;
node = node.left;
}
return height;
}
}
Count Complete Tree Nodes in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root) {
return 0;
}
// Get the height of the left and right subtrees.
// Height is defined as the number of nodes on the leftmost path.
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
if (leftHeight == rightHeight) {
// If heights are equal, the left subtree is a perfect binary tree.
// The total number of nodes is 1 (root) + (2^leftHeight - 1) (left subtree)
// + nodes in the right subtree.
// This simplifies to (1 << leftHeight) + countNodes(root->right).
return (1 << leftHeight) + countNodes(root->right);
} else {
// If leftHeight > rightHeight, the right subtree is a perfect binary tree.
// This is because in a complete tree, leftHeight can be at most rightHeight + 1.
// The total nodes are 1 (root) + nodes in left subtree + (2^rightHeight - 1) (right subtree).
// This simplifies to countNodes(root->left) + (1 << rightHeight).
return (1 << rightHeight) + countNodes(root->left);
}
}
private:
// Helper function to calculate the height of a tree by its leftmost path.
int getHeight(TreeNode* node) {
int height = 0;
while (node) {
height++;
node = node->left;
}
return height;
}
};
Count Complete Tree Nodes in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function countNodes(root: TreeNode | null): number {
if (!root) {
return 0;
}
// Helper function to calculate the height of a tree by its leftmost path.
const getHeight = (node: TreeNode | null): number => {
let height = 0;
while (node) {
height++;
node = node.left;
}
return height;
};
const leftHeight = getHeight(root.left);
const rightHeight = getHeight(root.right);
if (leftHeight === rightHeight) {
// If heights are equal, the left subtree is a perfect binary tree.
// The total number of nodes is 1 (root) + (2^leftHeight - 1) (left subtree)
// + nodes in the right subtree.
// This simplifies to (1 << leftHeight) + countNodes(root.right).
return (1 << leftHeight) + countNodes(root.right);
} else {
// If leftHeight > rightHeight, the right subtree is a perfect binary tree.
// This is because in a complete tree, leftHeight can be at most rightHeight + 1.
// The total nodes are 1 (root) + nodes in left subtree + (2^rightHeight - 1) (right subtree).
// This simplifies to countNodes(root.left) + (1 << rightHeight).
return (1 << rightHeight) + countNodes(root.left);
}
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.