코딩테스트/BFS,DFS

[leetCode] 572. Subtree of Another Tree

minkg3532 2026. 5. 29. 20:07

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

 

Subtree of Another Tree - LeetCode

Can you solve this real interview question? Subtree of Another Tree - 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 bin

leetcode.com

 

메인트리와 서브트리로 두 이진트리가 주어졌을 때, 해당 서브트리가 메인트리에 존재하면 true, 아니면 false를 반환하는 구조이다.

 

더보기
더보기

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSubtree(TreeNode* root, TreeNode* subRoot) 
    {
        if (root == nullptr) 
            return false;
        
        if(Search(root, subRoot))
            return true;

        return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);

    }

    bool Search(TreeNode* node, TreeNode* subNode)
    {
        if(node == nullptr && subNode == nullptr)
            return true;
    
        if(node == nullptr || subNode == nullptr || node->val != subNode->val)
            return false;
        
        return Search(node->left, subNode->left) && Search(node->right, subNode->right);
    }
};