Python coding

Every node k steps away

Write nodes_at_distance(root, start, k): return the values of every node exactly k edges away from the node start in a binary tree, in any order. Edges can be walked both ways, so the answer may include nodes above start and in other branches, not only below it; k = 0 gives just start, and a k larger than any distance gives []. Values are distinct, start is in the tree, and nodes have no link to their parent. Each TreeNode has val, left and right.

The tests call the provided run_nodes_at_distance(values, start, k), where values lists the tree level by level with null for a missing child ([1, null, 2, 3] is a root 1 with only a right child 2, whose left child is 3) and start is the value of the start node.

  • run_nodes_at_distance([8,4,12,2,6,10,14,1,3,5,7], 4, 2) → [12,1,3,5,7]
  • run_nodes_at_distance([1,2,null,3,null,4,null,5], 3, 2) → [1,5]
  • run_nodes_at_distance([8,4,12,2,6,10,14,1,3,5,7], 8, 0) → [8]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Going up is the hard direction, because nodes don't know their parent. One traversal can fill a dict from each node to its parent; then the tree is an undirected graph.

Hint 2

Now search breadth-first from start over left, right and parent, with a visited set so you never walk back. After k rounds, the current ring is the answer.

Solution and why it works
pythonO(n) · O(n)
# --- your code ---
def nodes_at_distance(root: "TreeNode", start: "TreeNode", k: int) -> list[int]:
    parent = {root: None}
    stack = [root]
    while stack:                         # one pass to learn every node's parent
        node = stack.pop()
        for child in (node.left, node.right):
            if child is not None:
                parent[child] = node
                stack.append(child)
    ring, seen = [start], {start}
    for _ in range(k):                   # BFS: each round moves one edge further out
        ring = [nb for node in ring for nb in (node.left, node.right, parent[node])
                if nb is not None and nb not in seen]
        seen.update(ring)
    return [node.val for node in ring]


# --- provided: do not edit ---
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def build_tree(values: list[int | None]) -> TreeNode | None:
    # Level order: each existing node takes the next two entries as its left and right child.
    nodes = [None if v is None else TreeNode(v) for v in values]
    children = iter(nodes[1:])
    for node in nodes:
        if node is not None:
            node.left = next(children, None)
            node.right = next(children, None)
    return nodes[0] if nodes else None


def find(root: TreeNode | None, val: int) -> TreeNode:
    stack = [root]
    while stack:
        node = stack.pop()
        if node is not None:
            if node.val == val:
                return node
            stack += [node.left, node.right]
    raise ValueError(f"{val} is not in the tree")


def run_nodes_at_distance(values: list[int | None], start: int, k: int) -> list[int]:
    root = build_tree(values)
    return nodes_at_distance(root, find(root, start), k)

Only the parent links are missing to treat the tree as an undirected graph, and one traversal fills a node → parent dict. A breadth-first search from start over left, right and parent then reaches nodes in order of distance, so after k rounds the current ring is the answer. The visited set matters: without it each step walks straight back to the node it came from. O(n) time and memory. Searching only below start misses every node reached by going up first.