From 860fa91880efc5d02d2b2ffa6b3db509b6038fea Mon Sep 17 00:00:00 2001 From: Kaushik Narayan R Date: Sat, 18 Nov 2023 15:22:33 -0700 Subject: [PATCH] day 39: 572-subtree-of-another-tree --- 572-subtree-of-another-tree/driver.cpp | 18 +++++++++++++ 572-subtree-of-another-tree/soln.cpp | 37 ++++++++++++++++++++++++++ 572-subtree-of-another-tree/soln.hpp | 20 ++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 572-subtree-of-another-tree/driver.cpp create mode 100644 572-subtree-of-another-tree/soln.cpp create mode 100644 572-subtree-of-another-tree/soln.hpp diff --git a/572-subtree-of-another-tree/driver.cpp b/572-subtree-of-another-tree/driver.cpp new file mode 100644 index 0000000..1203086 --- /dev/null +++ b/572-subtree-of-another-tree/driver.cpp @@ -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; +} \ No newline at end of file diff --git a/572-subtree-of-another-tree/soln.cpp b/572-subtree-of-another-tree/soln.cpp new file mode 100644 index 0000000..6882950 --- /dev/null +++ b/572-subtree-of-another-tree/soln.cpp @@ -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; +} \ No newline at end of file diff --git a/572-subtree-of-another-tree/soln.hpp b/572-subtree-of-another-tree/soln.hpp new file mode 100644 index 0000000..73d9066 --- /dev/null +++ b/572-subtree-of-another-tree/soln.hpp @@ -0,0 +1,20 @@ +#include +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); +}; \ No newline at end of file