반응형
1. 문제
- 이진 트리가 주어질 때, 구조가 같고 같은 값으로 이루어져 있는 노드의 배열을 반환하라.
2. 해결
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function findDuplicateSubtrees(root: TreeNode | null): Array<TreeNode | null> {
const map = new Map<string,number>();
const result = []
function DFS(node: TreeNode | null): string {
if(!node) return '';
const left = DFS(node.left);
const right = DFS(node.right);
const str = `${node.val},${left},${right}`
if(map.has(str)) {
if(map.get(str) === 1) result.push(node)
map.set(str, map.get(str)+1);
}
else map.set(str, 1);
return str;
}
DFS(root)
return result;
};
- map에 경로를 고유한 key로 저장해두고, 탐색 과정에서 이미 1개 있는 경우만 result에 담으면 중복 없이 들어간다.