[LeetCode] Subtree of Another Tree

아르당·2026년 1월 30일

LeetCode

목록 보기
121/134
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

두 개의 이진 트리 root와 subRoot가 주어졌을 때, root와 동일한 구조 및 노드 값을 가진 서브 트리가 존재하면 true, 그렇지 않다면 false를 반환해라.
이진 트리의 서브트리 tree는 트리의 노드 하나와 그 노드의 모든 자손으로 이루어진 트리이다. 트리 tree 자체도 서브트리로 간주될 수 있다.

Example

#1

Input: root = [3, 4, 5, 1, 2], subRoot = [4, 1, 2]
Output: true

#2

Input: root = [3, 4, 5, 1, 2, null, null, null, null, null, 0], subRoot = [4, 1, 2]
Output: false

Constraints

  • root 트리에 있는 노드의 수는 [1, 2000] 범위에 있다.
  • subRoot 트리에 있는 노드의 수는 [1, 1000] 범위에 있다.
  • -10^4 <= root.val <= 10^4
  • -10^4 <= subRoot.val <= 10^4

Solved

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null) return false;
        if(isSame(root, subRoot)) return true;

        return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
    }

    private boolean isSame(TreeNode root, TreeNode subRoot){
        if(root == null && subRoot == null) return true;
        if(root == null || subRoot == null) return false;
        if(root.val != subRoot.val) return false;

        return isSame(root.left, subRoot.left) && isSame(root.right, subRoot.right);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글