
이진 트리의 root, 타깃 노드 target, 정수 k 가 주어진다. target 에서 거리가 정확히 k 인 모든 노드의 값을 배열로 반환한다. 순서는 상관없다.
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
거리 k 인 노드는 target 의 아래(자식 방향)에만 있지 않다. 예시의 1 은 5 → 3 → 1 처럼 부모로 올라갔다가 다른 가지로 내려가야 닿는다.
그런데 이진 트리 노드에는 left, right 만 있고 부모로 가는 포인터가 없다. 그래서 두 단계로 푼다.
Map 에 기록한다.left, right, parent 세 방향으로 갈 수 있으니, 트리를 무방향 그래프처럼 보고 target 에서 BFS 를 k 단계 돌린다.BFS 는 한 단계에 거리 1씩 퍼지므로, k 번 확장한 뒤 남아 있는 노드들이 곧 답이다. 위아래로 모두 움직이기 때문에 왔던 노드로 되돌아가지 않도록 visited 로 막아야 한다.
function distanceK(root: TreeNode | null, target: TreeNode | null, k: number): number[] {
// 1. 자식 → 부모 관계 기록
const childToParent = new Map<TreeNode, TreeNode>();
const arr = [root];
while (arr.length) {
const cur = arr.pop();
for (const child of [cur.left, cur.right]) {
if (!child) continue;
childToParent.set(child, cur);
arr.push(child);
}
}
// 2. target 에서 BFS, 한 바퀴에 거리 1씩
let level = [target];
const visited = new Set<TreeNode>([target]);
for (let dist = 0; dist < k && level.length; dist++) {
const next: TreeNode[] = [];
for (const node of level) {
for (const child of [childToParent.get(node), node.left, node.right]) {
if (child && !visited.has(child)) {
visited.add(child);
next.push(child);
}
}
}
level = next;
}
return level.map(node => node.val);
};
k = 0 이면 반복문을 돌지 않으므로 [target.val] 이 그대로 반환된다.level 이 비면 반복을 멈추고 [] 를 반환한다. (root = [1], k = 3 같은 경우)childToParent.get(root) 는 undefined 이고, if (child && ...) 에서 걸러진다.처음에는 아래처럼 target 노드를 Map 에서 꺼내 썼다.
const targetNode = childToParent.get(target);
let level = [targetNode];
TypeError: Cannot read properties of undefined (reading 'left')
childToParent.get(target) 은 target 자신이 아니라 target 의 부모를 돌려준다. target 이 root 면 부모가 없어서 undefined 가 되어 위 에러가 났다. root 가 아니어도 부모에서 BFS 를 시작하니 거리가 1씩 어긋난다.
LeetCode 의 TS 시그니처에서 target 은 값이 아니라 이미 TreeNode 이므로 그대로 시작점으로 쓰면 된다.