Number of Good Leaf Nodes Pairs

MediumTreestree dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the root of a binary tree and an integer distance. A pair of two **different** leaf nodes is **good** when the number of edges on the shortest path between them is at most distance. Return the number of good leaf pairs. Each unordered pair is counted once. A tree consisting of a single node has one leaf and therefore no pairs.

Examples

Input: root = [1,2,3,null,4], distance = 3
Output: 1
The leaves 4 and 3 are three edges apart (4-2-1-3).
Input: root = [1,2,3,4,5,6,7], distance = 3
Output: 2
Sibling leaves (4,5) and (6,7) are two edges apart; cross pairs are four edges apart.
Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3
Output: 1
The leaves are 6, 5 and 2. Only 5 and 2 are within three edges (5-4-3-2).

Constraints

  • 1 <= number of nodes <= 2^10
  • 1 <= Node.val <= 100
  • 1 <= distance <= 10

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More tree dp problems