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);
}
};
'코딩테스트 > BFS,DFS' 카테고리의 다른 글
| [leetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal (0) | 2026.05.29 |
|---|---|
| [leetCode] 230. Kth Smallest Element in a BST (0) | 2026.05.29 |
| [leetCode] 297. Serialize and Deserialize Binary Tree (0) | 2026.05.29 |
| [leetCode] 79. Word Search (0) | 2026.05.29 |
| [leetCode] 1376. Time Needed to Inform All Employees (0) | 2026.05.29 |