Skip to content

Commit

Permalink
Added Same Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 16, 2023
1 parent b4b9761 commit c454038
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -755,4 +755,15 @@ add_executable(MaximumDepthOfBinaryTree
target_link_libraries(
MaximumDepthOfBinaryTree
GTest::gtest_main
)

# Same Tree
add_executable(SameTree
Easy/SameTree/include/solution.hpp
Easy/SameTree/tests/test.cpp
)

target_link_libraries(
SameTree
GTest::gtest_main
)
31 changes: 31 additions & 0 deletions Easy/SameTree/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#pragma once

#include <vector>
#include <iostream>
#include <algorithm>
#include <gtest/gtest.h>

struct TreeNode {
int32_t value;
TreeNode *left;
TreeNode *right;
explicit TreeNode(int32_t value) :
value(value), left(nullptr), right(nullptr) { }
};

class Solution {
public:
static auto is_same_tree(TreeNode *p, TreeNode *q) -> bool {
static std::function<bool(TreeNode*, TreeNode*)> is_same_tree_impl =
[&](TreeNode *p, TreeNode *q) -> bool {
if (p == nullptr && q == nullptr) return true;
if (p == nullptr || q == nullptr) return false;
if (p->value == q->value) {
return is_same_tree_impl(p->left, q->left) &&
is_same_tree_impl(p->right, q->right);
}
return false;
};
return is_same_tree_impl(p, q);
}
};
15 changes: 15 additions & 0 deletions Easy/SameTree/tests/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include "../include/solution.hpp"

auto main() -> int {
auto *p = new TreeNode(1);
p->left = new TreeNode(2);
p->right = new TreeNode(3);

auto *q = new TreeNode(1);
q->left = new TreeNode(2);
q->right = new TreeNode(3);

std::cout << std::boolalpha << Solution::is_same_tree(p, q);

return 0;
}

0 comments on commit c454038

Please sign in to comment.