All problems

Problem 413

All Nodes at Distance K

Medium · 20 pts · Tree, Breadth-First Search, Depth-First Search, Hash Table

Problem

Given a binary tree with distinct values, a target value that appears in it, and a distance K, find every node exactly K edges away from the target node. The path may go up through parents as well as down through children. Print the values in increasing order, or NONE if there are none. Turning the tree into an undirected graph (adding parent links) and running a breadth-first search from the target is a clean approach.

Input

The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode. The third line contains the target value and K.

Output

Print the matching values in increasing order, separated by spaces, or NONE.

Constraints

1 <= number of nodes <= 500; values are distinct; 0 <= K <= 1000

Example input

11
3 5 1 6 2 0 8 null null 7 4
5 2

Example output

1 4 7

Explanation

In the tree 3 / 5 1 / 6 2 0 8 / _ _ 7 4 with target 5 and K = 2, the nodes two edges away are 7 and 4 (below 5) and 1 (through the root).

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Distribute Coins in a Binary Tree Next: Boundary Traversal of Binary Tree