AlgoFrames

Count the nodes at depth d

Standard · Write code · about 8 min

Given the root of a binary tree and a number d, return how many nodes have depth exactly d. The root has depth 0, its children depth 1, and so on. Return 0 when the tree has no level d.

Example 1

Input:

[[1,2,3,4,5,null,6,null,null,7],2]

Output:

3

Depth 2 holds 4, 5 and 6.

Example 2

Input:

[[3,9,20,null,null,15,7],1]

Output:

2

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
  • 0 ≤ d ≤ 1,000

Learn the idea first: Trees: root, leaf, depth, height, subtree, a visual lesson.

More Trees: root, leaf, depth, height, subtree problems