33. All Nodes Distance K in Binary Tree

We are given a binary tree (with root node root), a target node, and an integer value K.

Return a list of the values of all nodes that have a distance K from the target node. The answer can be returned in any order.

Example 1:

Solution:

Approach: If we know the parent of every node x, we know all nodes that are distance 1 from x Using 2 BFS 1. Storing Parents of each node in map 2. Finding all nodes at a distance k from target

Time Complexity: o(n)

Last updated

Was this helpful?