mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 05:24:07 +00:00
day 39: 572-subtree-of-another-tree
This commit is contained in:
parent
0706e1953c
commit
860fa91880
18
572-subtree-of-another-tree/driver.cpp
Normal file
18
572-subtree-of-another-tree/driver.cpp
Normal file
@ -0,0 +1,18 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
int main()
|
||||
{
|
||||
// input
|
||||
TreeNode n1 = TreeNode(1);
|
||||
TreeNode n3 = TreeNode(3);
|
||||
TreeNode n6 = TreeNode(6);
|
||||
TreeNode n9 = TreeNode(9);
|
||||
TreeNode n2 = TreeNode(2, &n1, &n3);
|
||||
TreeNode n7 = TreeNode(7, &n6, &n9);
|
||||
TreeNode n4 = TreeNode(4, &n2, &n7);
|
||||
bool answer = true;
|
||||
|
||||
Solution soln;
|
||||
cout << "Checked subtree correctly? " << soln.test(&n4, &n7, answer) << endl;
|
||||
return 0;
|
||||
}
|
||||
37
572-subtree-of-another-tree/soln.cpp
Normal file
37
572-subtree-of-another-tree/soln.cpp
Normal file
@ -0,0 +1,37 @@
|
||||
#include "soln.hpp"
|
||||
|
||||
bool Solution::isIdenticalTree(TreeNode *t1, TreeNode *t2)
|
||||
{
|
||||
if (!t1 || !t2)
|
||||
{
|
||||
return t1 == nullptr && t2 == nullptr;
|
||||
}
|
||||
else if (t1->val == t2->val)
|
||||
{
|
||||
return isIdenticalTree(t1->left, t2->left) && isIdenticalTree(t1->right, t2->right);
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
bool Solution::isSubtree(TreeNode *root, TreeNode *subRoot)
|
||||
{
|
||||
if (!root)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if (isIdenticalTree(root, subRoot))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);
|
||||
}
|
||||
}
|
||||
|
||||
bool Solution::test(TreeNode *root, TreeNode *subRoot, bool answer)
|
||||
{
|
||||
return isSubtree(root, subRoot) == answer;
|
||||
}
|
||||
20
572-subtree-of-another-tree/soln.hpp
Normal file
20
572-subtree-of-another-tree/soln.hpp
Normal file
@ -0,0 +1,20 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
|
||||
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 isIdenticalTree(TreeNode *t1, TreeNode *t2);
|
||||
bool isSubtree(TreeNode *root, TreeNode *subRoot);
|
||||
bool test(TreeNode *root, TreeNode *subRoot, bool answer);
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user