FastPrepAll Nodes Distance K in a Binary Tree
Problem · Tree

All Nodes Distance K in a Binary Tree

Learn this problem
MediumAmazon logoAmazonFULLTIMEPHONE SCREEN
See Amazon hiring insights

Problem statement

You are given the root of a binary tree whose node values are unique, an integer target equal to one node value, and a nonnegative integer k.

Two directly connected tree nodes are one edge apart. Return the values of every node whose shortest-path distance from the target node is exactly k.

Return the values in ascending order. If no node is exactly k edges away, return an empty list.

Function

distanceK(root: TreeNode, target: int, k: int) → List<Integer>

Examples

Example 1

root = [3,5,1,6,2,0,8,null,null,7,4]target = 5k = 2return = [1,4,7]

From node 5, nodes 7 and 4 are reached through node 2, while node 1 is reached through node 3. Each is two edges away.

Example 2

root = [1]target = 1k = 0return = [1]

The target node itself is the only node at distance 0.

Constraints

  • The tree contains between 1 and 500 nodes.
  • 0 <= Node.val <= 500.
  • Every node value is unique.
  • target is the value of a node in the tree.
  • 0 <= k <= 1000.

More Amazon problems

drafts saved locally
public List<Integer> distanceK(TreeNode root, int target, int k) {
    // Write your solution here.
}
root[3,5,1,6,2,0,8,null,null,7,4]
target5
k2
expected[1,4,7]
checking account