15% off all plans & roadmaps Use code

See plans

All Nodes Distance K in Binary Tree

Updated

TL;DR: Given a target node in a binary tree, return the values of every node exactly k edges away. A postorder DFS that returns each node's distance to the target finds them in one pass.

Problem

Given the root of a binary tree, the value of a target node, and an integer k, return an array of the values of all nodes that are at distance k from the target node.

You can return the answer in any order.

Example 1

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

Output: [7,4,1]

Explanation: The nodes at distance 2 from the target node (value 5) have values 7, 4, and 1.

Example 2

Input: root = [1], target = 1, k = 3

Output: []

Constraints

  • The number of nodes in the tree is in the range [1, 500].
  • 0 <= Node.val <= 500
  • All the values Node.val are unique.
  • target is the value of one of the nodes in the tree.
  • 0 <= k <= 1000

Constraints that matter

  • Up to 500 nodes means an O(n) pass is comfortably fast. The algorithm only needs to touch each node a constant number of times.
  • k can be up to 1000, far more than the tree height in most inputs. The search must stop cleanly when the remaining distance goes negative.
  • The tree has no parent pointers, so you cannot walk up from the target for free. You need either a parent map or a DFS that carries distances upward.
  • Values are unique, so the target can be found by comparing node references. You do not need to compare values.

View on LeetCode

Hints

Hint 1

A binary tree only links a node to its children.

Hint 2

Treat the tree as an undirected graph.

Solution

Intuition

A binary tree only links a node to its children. From the target you can go down freely, but going up or sideways requires a way to find ancestors. Every node at distance k is reached in one of two ways. It lies straight down from the target, or it sits up some number of steps at a common ancestor and then down the other branch.

It is like a relay of messengers climbing back up a family tree. Each parent reads the distance the messenger brought, then sends a second messenger down the other branch for the remaining steps.

The pattern is tree DFS with postorder-style return values. A node cannot know its distance to the target until its children report back. So each call returns a number that its parent reads. The information flows upward, which is the defining move of postorder traversal.

The math is short. If the target sits under the left child of a node, and that child reports distance L, then the node is L away. Its right child is L + 1 away. Nodes at depth k - L - 1 below the right child are exactly k away. Because a tree has one path between any two nodes, each answer is found once.

Watch the pattern animation

Worked example

Input: root = [1], target = 1, k = 3
Output: []
Explanation: The tree has one node, and it is the target. No node sits 3 edges away from it, so the answer is empty. The same input with k = 0 would return [1].

Approach 1: Parent map and BFS

Treat the tree as an undirected graph. A binary tree links each node only to its children. The first pass records each node's parent, which adds the upward edges. Then run a breadth-first search from the target. BFS visits nodes in order of distance, so the nodes you dequeue at distance k are the answer. You stop expanding once you reach distance k.

Steps

  1. Walk the tree once and store each child's parent in a map.
  2. Put the target into a queue with distance 0, and mark it seen.
  3. Dequeue a node. If its distance equals k, add its value to the result and skip its neighbours.
  4. Otherwise, push each unseen neighbour (left child, right child, parent) with distance plus one.
  5. Return the result when the queue is empty.

Dry run

The root has no children, so the parent map stays empty. The queue starts as [(1, 0)] with seen = {1}.

Dequeue (1, 0). Its distance 0 is not 3, so keep going. Its left child, right child and parent are all missing, so nothing is pushed.

The queue is empty. The result is []. The output matches the example.

Complexity

TimeO(n)
SpaceO(n)

Let n be the number of nodes. The first pass pushes and pops each node once, so it does n steps. BFS marks a node as seen before queueing it, so each node enters the queue at most once and each dequeue does constant work. The parent map, seen set and queue each hold at most n entries, so the extra space is O(n).

PythonTested in our runner

from typing import List, Optional
from collections import deque

class Solution:
    def distanceK(self, root: Optional[TreeNode], target: Optional[TreeNode], k: int) -> List[int]:
        # Pass 1: record each node's parent
        parent = {}
        stack = [root]
        while stack:
            node = stack.pop()
            if node.left:
                parent[node.left] = node
                stack.append(node.left)
            if node.right:
                parent[node.right] = node
                stack.append(node.right)

        # Pass 2: BFS from target over child and parent links
        queue = deque([(target, 0)])
        seen = {target}
        result = []
        while queue:
            node, dist = queue.popleft()
            if dist == k:
                result.append(node.val)
                continue
            for nxt in (node.left, node.right, parent.get(node)):
                if nxt is not None and nxt not in seen:
                    seen.add(nxt)
                    queue.append((nxt, dist + 1))
        return result

The Recursive Postorder Traversal infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Recursive Postorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 2: Postorder DFS returning distancesOptimalRecursive Postorder Traversal

What's slow in the first approach: the parent map and seen set use O(n) extra memory. BFS also explores a graph built from links the recursion already walks. The insight that fixes it: a DFS unwinds back through every ancestor of the target. Each ancestor reads its child's return value to learn its own distance. It then searches the opposite child for the remaining distance. No map is needed, because the call stack holds the path.

Steps

  1. Write collectDown(node, d) that adds every node exactly d edges below node. Return immediately if node is null or d is negative.
  2. Write findDistance(node). Return -1 if node is null.
  3. If node is the target, call collectDown(node, k) and return 1, the distance from the target's parent.
  4. Otherwise recurse into the left child. If it returns L other than -1, then node is L away. If L equals k, add node. Otherwise call collectDown(right, k - L - 1). Return L + 1.
  5. If the left side returned -1, do the same with the right child and collectDown(left, k - R - 1).
  6. Return -1 when the target is not below node. Call findDistance(root) and return the result.

Dry run

Trace on the example, root = [1], target = 1, k = 3. The table has one row per call.

StepCallActionResultReturns
1findDistance(1)node is the target, so call collectDown(1, 3)[]1
2collectDown(1, 3)both children are null, so nothing is added[]none
3top-level call endsno more nodes to visit[]done

The output is []. The example is too small to show the upward step. Here is Example 1 from the statement instead, with target 5 and k = 2.

StepCallActionResultReturns
1findDistance(3)not the target, so recurse left[]waiting
2findDistance(5)node is the target, so collectDown(5, 2) adds 7 and 4[7, 4]1
3findDistance(3)left returned L = 1, which is not 2, so collectDown(1, 0) adds 1[7, 4, 1]2

The output is [7, 4, 1].

Complexity

TimeO(n)
SpaceO(h)

Let n be the number of nodes and h the height. findDistance enters each node once, so it makes n calls of constant work. collectDown runs only on the target's subtree and on sibling subtrees beside the path to the target. Those subtrees are disjoint, so each node is visited by at most one collectDown call. The recursion never goes deeper than h, so the stack uses O(h) space. In the worst case that is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def distanceK(self, root: Optional[TreeNode], target: Optional[TreeNode], k: int) -> List[int]:
        result = []

        # Adds nodes exactly dist edges below node
        def collect_down(node, dist):
            if node is None or dist < 0:
                return
            if dist == 0:
                result.append(node.val)
                return
            collect_down(node.left, dist - 1)
            collect_down(node.right, dist - 1)

        # Returns the distance from node's parent to target, or -1 if target is not below node
        def find_distance(node):
            if node is None:
                return -1
            if node is target:
                collect_down(node, k)
                return 1
            left = find_distance(node.left)
            if left != -1:
                if left == k:
                    result.append(node.val)
                else:
                    collect_down(node.right, k - left - 1)
                return left + 1
            right = find_distance(node.right)
            if right != -1:
                if right == k:
                    result.append(node.val)
                else:
                    collect_down(node.left, k - right - 1)
                return right + 1
            return -1

        find_distance(root)
        return result

Common mistakes

  • collect_down(node.right, k - left) with no minus one. The edge from node to its right child adds a step, so the remaining distance is k - left - 1.
  • return 0 when node is the target. The parent needs the distance from itself to the target, which is 1 for the target's parent, so return 1.
  • Searching the other child after one side already reported a distance. The target is unique, so the other side can never hold it. Return right away and skip the extra recursion.
  • A BFS without a seen check, so parent.get(node) pushes the node you came from. The search bounces between two nodes until the distance limit stops it. Add the seen test before every push.
  • Skipping the left == k test. The ancestor at distance k is an answer, and searching only the sibling side misses it. Add the ancestor before searching the other side.

Edge cases

  • A single node with k = 0 returns the target's value, because the target is at distance 0 from itself.
  • A single node with k greater than 0 returns an empty list, since there are no other nodes.
  • The target is the root and k = 1. The answer is both children's values, found through collectDown on each side.
  • k is larger than the tree height. The answer is empty, and the null checks in collectDown stop the recursion without error.
  • The target is a leaf, as 4 in Example 1, and k = 2. The answer is 7 and 5, which are the sibling 7 and the grandparent-side ancestor 5, returned in any order.
  • A deep chain with k = 0 on a middle node. Only that node's value is returned, and no ancestor or descendant is added.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve All Nodes Distance K in Binary Tree, with how to answer them.

Unlock the follow-ups

All Nodes Distance K in Binary Tree FAQ

What is the time complexity of All Nodes Distance K in Binary Tree?

Both approaches run in O(n) time, where n is the number of nodes. The postorder DFS visits each node a constant number of times, and its helper calls cover disjoint subtrees.

Why use postorder DFS for All Nodes Distance K in Binary Tree?

A node needs its child's answer before it can decide anything, so information flows upward. Returning the distance to the target lets each ancestor find its own distance and search its other side without parent pointers.

Can All Nodes Distance K in Binary Tree be solved in O(1) extra space?

No, not with either approach on this page. The DFS needs O(h) stack space, and the BFS needs O(n) for the parent map. Reaching O(1) requires Morris-style threading that changes the tree, which is rarely worth it in an interview.

Do I need to build a graph for All Nodes Distance K in Binary Tree?

No. The tree already gives you child links, and the DFS covers upward moves with return values. Building a graph is simpler to reason about, but it costs O(n) extra memory.

Is it safe to compare TreeNode objects with == in Python?

Yes. TreeNode does not define equality, so == and is both compare identity, which is what you want. The DFS solution uses is to make that explicit.

Asked at

See which companies ask this — Pro

Practise it