All Nodes Distance K in Binary Tree

Medium · Trees · Hash Table · Tree · Depth-First Search · Breadth-First Search · Binary Tree

Problem

You are given the root of a binary tree whose values are all different, a node target of that tree, and an integer k.

Return the values of every node exactly k edges away from target. Distance is counted along tree edges, so a path may go up through parents as well as down through children. The values may be returned in any order.

The tests give the tree in level order (None for a missing child) and the target by its value; they build the tree and find the target node for you.

Examples

Input: root = [1,2,3,4,5,6,7], target = 2, k = 2
Output: [3]

Up from 2 to 1, then down to 3: two edges. 2's own children are only one edge away.

Input: root = [1,2,3,4,5,6,7], target = 4, k = 3
Output: [3]

The path 4 → 2 → 1 → 3 has three edges; 6 and 7 are four away.

Input: root = [1,2], target = 2, k = 0
Output: [2]

At distance zero the only node is the target itself.

Constraints

Approaches

Follow-up

Can you do it without a parent map? A recursive walk can return the distance from each subtree to the target; on the way back up, each ancestor at distance d collects the nodes k - d - 1 levels down its other side. It uses only the recursion stack.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…