21 · Tree Traversals

#863 All Nodes Distance K in Binary Tree

Mediumsolve on LeetCode ↗

frequently reported atMetaAmazonMicrosoftGoogleBloomberg

the problem

In plain words

You get the root, a node target inside the tree, and an integer k. Return the values of all nodes exactly k edges away from target — moving up to parents as well as down to children. Any order is fine.

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

out [7,4,1]

7 and 4 are two steps down from 5; 1 is up to 3, then down.

in root = [1], target = 1, k = 3

out []

  • 1 ≤ number of nodes ≤ 500
  • 0 ≤ Node.val ≤ 500, all values unique
  • target is a node of the tree
  • 0 ≤ k ≤ 1000

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #236
    2. #994
      Rotting Oranges
      Mediumin Graphs
    3. #102