222. Count Complete Tree Nodes LeetCode Solution
In this guide, you will get 222. Count Complete Tree Nodes LeetCode Solution with the best time and space complexity. The solution to Count Complete Tree Nodes problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Count Complete Tree Nodes solution in C++
- Count Complete Tree Nodes solution in Java
- Count Complete Tree Nodes solution in Python
- Additional Resources
Problem Statement of Count Complete Tree Nodes
Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Design an algorithm that runs in less than O(n) time complexity.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: 6
Example 2:
Input: root = []
Output: 0
Example 3:
Input: root = [1]
Output: 1
Constraints:
The number of nodes in the tree is in the range [0, 5 * 104].
0 <= Node.val <= 5 * 104
The tree is guaranteed to be complete.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(h)
222. Count Complete Tree Nodes LeetCode Solution in C++
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr)
return 0;
return 1 + countNodes(root->left) + countNodes(root->right);
}
};
/* code provided by PROGIEZ */
222. Count Complete Tree Nodes LeetCode Solution in Java
class Solution {
public int countNodes(TreeNode root) {
if (root == null)
return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
// code provided by PROGIEZ
222. Count Complete Tree Nodes LeetCode Solution in Python
class Solution:
def countNodes(self, root: TreeNode | None) -> int:
if not root:
return 0
return 1 + self.countNodes(root.left) + self.countNodes(root.right)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.