572. Subtree of Another Tree(Tree, DFS, String Matching, Binary Tree, Hash Function)*

YAMAMAMO·2022년 12월 3일
0

LeetCode

목록 보기
89/100

문제

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.
A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.

https://leetcode.com/problems/subtree-of-another-tree/description/

Example 1:

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

Example 2:

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

문제

class Solution {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root==null) return false;
        if(findSubtree(root, subRoot)) return true;
        return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
    }

    public boolean findSubtree(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  findSubtree(root.left, subRoot.left)
            &&findSubtree(root.right, subRoot.right);
    }
}
profile
안드로이드 개발자

0개의 댓글