↓Skip to main content
  1. LeetCode/

LeetCode 863: All Nodes Distance K in Binary Tree

·2 mins· ·
LeetCode Medium Hash-Table Tree Depth-First-Search Breadth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-10-28

  • Submissions: Accepted (first try)

Approach
#

A node at distance k may be inside target’s subtree, or reached by first going up to an ancestor and then down. A tree only has downward pointers, so first turn it into an undirected graph (Tree Template 5): one DFS records every parent-child edge in both directions. Values are unique, so they can serve as graph nodes.

Then BFS from target; the nodes at level k are the answer.

My Attempts
#

Accepted on the first try.

Solution
#

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

        def dfs(node):
            for child in (node.left, node.right):
                if child:
                    adj[node.val].append(child.val)
                    adj[child.val].append(node.val)
                    dfs(child)

        dfs(root)
        seen = {target.val}
        level = [target.val]
        for _ in range(k):
            nxt = []
            for node in level:
                for nei in adj[node]:
                    if nei not in seen:
                        seen.add(nei)
                        nxt.append(nei)
            level = nxt
        return level

My submission checked seen when popping and stopped once dist > k, which gives the same result; this version marks nodes when they are queued, so no node enters the queue twice.

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Searching only downward misses nodes reached through the parent.
  • Keep a seen set; an undirected graph lets BFS walk back.
  • Storing just parent pointers also works, without a full adjacency list.

Interview Explanation
#

Nodes at distance k may require going up first, so I DFS once to turn the tree into an undirected graph with both directions of every parent-child edge. Then I BFS from target with a seen set, and after k levels the nodes in the frontier are the answer. Time and space O(n).

Related

LeetCode 314: Binary Tree Vertical Order Traversal
·2 mins
LeetCode Medium Hash-Table Tree Depth-First-Search Breadth-First-Search Sorting Binary-Tree
LeetCode 314 note: BFS with a column index; BFS is what guarantees top-to-bottom within a column and left-to-right within a row
LeetCode 652: Find Duplicate Subtrees
·2 mins
LeetCode Medium Hash-Table Tree Depth-First-Search Binary-Tree
LeetCode 652 note: encode every subtree in post-order and report it on its second occurrence; string keys are O(n^2) worst case, (val, left id, right id) ids make it O(n)
LeetCode 449: Serialize and Deserialize BST
·2 mins
LeetCode Medium String Tree Depth-First-Search Breadth-First-Search Design Binary-Search-Tree Binary-Tree
LeetCode 449 note: for a BST, pre-order without null markers is enough; deserialize recursively with bounds in O(n)
LeetCode 515: Find Largest Value in Each Tree Row
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 515 note: BFS level order, taking the maximum of each level; start from -inf
LeetCode 117: Populating Next Right Pointers in Each Node II
·2 mins
LeetCode Medium Linked-List Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 117 note: connect next pointers level by level with BFS; for a non-perfect tree, looking only at the neighbour’s children breaks the chain
LeetCode 1448: Count Good Nodes in Binary Tree
·1 min
LeetCode Medium Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 1448 note: pass the path maximum down during DFS; a node is good when its value is at least that maximum