Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Count Nodes in Binary Tree

Medium Acceptance 64% Points 30

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.

Examples
Example 1

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

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

Example 3

Input: root = []

Output: 0

Explanation: If the tree is empty, there are no nodes, so the count is 0.

Constraints
  • 0 = number of nodes = 105
  • -104 = Node.val = 104
Topics
Recursion
Companies
Microsoft Apple
Added 19 Jul 2026 64% acceptance
Ln 1, Col 1Sign in to save your code
1
1