From ec2b3df836eafd41379d3d9d20fd2ec507dce61a Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 10 Jan 2023 23:16:12 +0100 Subject: [PATCH] =?UTF-8?q?problems(cpp):=20add=20=E2=80=9E100.=20Same=20T?= =?UTF-8?q?ree=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/same-tree.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 problems/same-tree.cpp diff --git a/problems/same-tree.cpp b/problems/same-tree.cpp new file mode 100644 index 0000000..8ec70c0 --- /dev/null +++ b/problems/same-tree.cpp @@ -0,0 +1,30 @@ +/** + * 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 isSameTree(TreeNode* p, TreeNode* q) + { + if (p == nullptr && q == nullptr) { + return true; + } + + if (p == nullptr || q == nullptr) { + return false; + } + + if (p->val != q->val) { + return false; + } + + return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } +};