Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Find Nodes at Distance K from Given Node

Hard Acceptance 65.95% Points 40

You are given the root of a binary tree, the value of a target node, and an integer k. Your task is to return all node values that are exactly k edges away from the target node.

A node can be reached by moving:

  • To its left child
  • To its right child
  • To its parent

Return all nodes whose shortest distance from the target node is exactly k.

Examples
Example 1

image Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation: The nodes 7, 4, and 1 are exactly 2 edges away from node 5.

Example 2

image Input: root = [1], target = 1, k = 0
Output: [1]
Explanation: The target node is at distance 0 from itself.

Example 3

image Input: root = [1,2,3], target = 2, k = 2
Output: [3]
Explanation: Node 3 is exactly 2 edges away from node 2.

Constraints
    • 1 = Number of nodes = 105
    • -10? = Node.data = 10?
    • 0 = k = 105
Topics
Tree Traversal Binary Tree
Companies
Apple DE Shaw Wayfair
Added 08 Aug 2026 65.95% acceptance
Ln 1, Col 1Sign in to save your code
1 2 3 4 5 6 7
2 2
4 5 3