Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
K Distance Nodes in Tree
00:00
5 left

K Distance Nodes in Tree

MediumPython

Problem

Find the k distance nodes in a binary tree.

Implement distance_k_nodes(root, target, k), where root is a nested binary tree dictionary, target is a unique node value, and k is a nonnegative distance. Return node values exactly k edges from the target, ordered by BFS discovery using left child, right child, then parent links. Return [] if the tree is empty, the target is absent, or no nodes are at that distance.

Each node has the form {"val": value, "left": node_or_null, "right": node_or_null}.

Constraints

  • 0 <= number of nodes <= 1000
  • Node values are integers
  • Node values are unique
  • 0 <= k <= 1000
  • Each node has keys val, left, and right
  • The tree contains no cycles

Function Signature

def distance_k_nodes(root, target, k):
Interviewer

Your question is K Distance Nodes in Tree. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
You need to log in / sign up to run or submit.Ln 2
Run your code to see test output here.