SDE & MLE Prep

863. All Nodes Distance K in Binary Tree

Problem

Given a binary tree, a target node and an integer k, return the values of all nodes exactly k edges away from target (up through parents as well as down), in any order.

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

Turn the tree into an undirected graph by recording each node's parent, then BFS from target for exactly k steps.

Complexity: O(n).

class Solution:
    def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
        parent = {root: None}
        st = [root]
        while st:
            node = st.pop()
            for c in (node.left, node.right):
                if c:
                    parent[c] = node
                    st.append(c)
        q, seen = deque([target]), {target}
        for _ in range(k):
            for _ in range(len(q)):
                node = q.popleft()
                for nb in (node.left, node.right, parent[node]):
                    if nb and nb not in seen:
                        seen.add(nb)
                        q.append(nb)
        return [n.val for n in q]