Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Find Nodes at Distance K from Given Node

Hard Acceptance 65.95% Points 40.00

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
Companies
Apple DE Shaw Wayfair
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions