Given the root of a binary tree, return the total number of nodes in the tree.
Each node in the tree contains a value and may have a left child, a right child, or both. The task is to count all nodes present in the tree, including the root.
Example 1
Input: root = [1,2,3,4,5,6]
Output: 6
Explanation: The tree contains six nodes: 1, 2, 3, 4, 5, and 6. Therefore, the total node count is 6.
Example 2
Input: root = [1,null,2]
Output: 2
Explanation: The tree has two nodes: 1 and 2. Hence, the total count is 2.
Example 3
Input: root = []
Output: 0
Explanation: If the tree is empty, there are no nodes, so the count is 0.
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
1
1
1 2 3
3