AlgoFrames

Count the nodes

Standard · Write code · about 6 min

Given the root of a binary tree, return the number of nodes in it. Each node has val, left and right; a missing child is null.

Example 1

Input:

[[8,3,10,1,6,null,14]]

Output:

6

8, 3, 10, 1, 6 and 14.

Example 2

Input:

[[1,null,2,3]]

Output:

3

Constraints

  • 0 ≤ number of nodes ≤ 1,000
  • -1,000 ≤ Node.val ≤ 1,000
  • The tree is given in level order; null marks a missing child

Learn the idea first: Binary trees and how they are stored, a visual lesson.

More Binary trees and how they are stored problems