[LeetCode] 652. Find Duplicate Subtrees, Medium

2025. 4. 9. 14:22·CodingTest/LeetCode
반응형

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에 담으면 중복 없이 들어간다. 
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 3. Longest Substring Without Repeating Characters, Medium
  • [LeetCode] 771. Jewels and Stones, Easy
  • [LeetCode] 36. Valid Sudoku, Medium
  • [LeetCode] 49. Group Anagrams, Medium
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    boj1427
    백준1427
    TypeScript
    leetcode 2236
    medium
    BOJ
    프로그래머스
    Java
    next 14
    백준2751
    meidum
    자바
    알고리즘
    백준1260
    component-scan
    boj2108
    백준7576
    Easy
    백준
    백준7576자바
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 652. Find Duplicate Subtrees, Medium
상단으로

티스토리툴바