Problem 414008 · hard · Level 04 Non-Linear Data Structures

Nodes Exactly k Edges From a Target

binary tree · breadth-first search · hash map · graphs

A tree holds distinct integers. Given the value target of one node and a distance k, return the values of all nodes that are exactly k edges away from the target node. Moving up to a parent counts as an edge just like moving down to a child. The values may be returned in any order; return [] if no node qualifies.

Examples

          8
        /   \
       3     14
      /     /  \
     1     11   17
    / \      \
   0   2      12

Input:  root = build_tree([8, 3, 14, 1, None, 11, 17, 0, 2, None, 12]), target = 14, k = 2
Output: [12, 3]
Explanation: 12 lies two edges below 14 (through 11); 3 is reached by going up to 8 and down again.

Input:  root = build_tree([8, 3, 14, 1, None, 11, 17, 0, 2, None, 12]), target = 8, k = 0
Output: [8]

Constraints

  • 1 <= number of nodes <= 1000
  • 0 <= k <= 1000
  • All values are distinct and target is present

Goals

  • Turn a tree into an undirected graph by recording each node's parent
  • Run a breadth-first search that can move up as well as down
Starting Python…