diff --git a/CMakeLists.txt b/CMakeLists.txt index d3e4994..4368ff6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1338,4 +1338,15 @@ add_executable(Leaf-SimilarTrees target_link_libraries( Leaf-SimilarTrees GTest::gtest_main +) + +# Count Good Nodes in Binary Tree +add_executable(CountGoodNodesInBinaryTree + Medium/CountGoodNodesInBinaryTree/include/solution.hpp + Medium/CountGoodNodesInBinaryTree/tests/test.cpp +) + +target_link_libraries( + CountGoodNodesInBinaryTree + GTest::gtest_main ) \ No newline at end of file diff --git a/Medium/CountGoodNodesInBinaryTree/include/solution.hpp b/Medium/CountGoodNodesInBinaryTree/include/solution.hpp new file mode 100644 index 0000000..b6052c0 --- /dev/null +++ b/Medium/CountGoodNodesInBinaryTree/include/solution.hpp @@ -0,0 +1,36 @@ +#pragma once + +#include +#include +#include +#include + +struct TreeNode { + const int32_t value; + TreeNode *left; + TreeNode *right; + explicit TreeNode(const int32_t value) : + value(value), left(nullptr), right(nullptr) { } +}; + +class Solution { +public: + static auto good_nodes(TreeNode *root) -> size_t { + std::function preorder = + [&](TreeNode *node, int32_t curr_max) -> void { + if (node == nullptr) return; + if (node->value >= curr_max) { + ++_count; + curr_max = node->value; + } + preorder(node->left, curr_max); + preorder(node->right, curr_max); + }; + + preorder(root, root->value); + return _count; + } + +private: + static size_t _count; +}; diff --git a/Medium/CountGoodNodesInBinaryTree/tests/test.cpp b/Medium/CountGoodNodesInBinaryTree/tests/test.cpp new file mode 100644 index 0000000..30d58b3 --- /dev/null +++ b/Medium/CountGoodNodesInBinaryTree/tests/test.cpp @@ -0,0 +1,14 @@ +#include "../include/solution.hpp" + +auto main() -> int { + auto *root = new TreeNode(3); + root->left = new TreeNode(1); + root->left->left = new TreeNode(3); + root->right = new TreeNode(4); + root->right->right = new TreeNode(5); + root->right->left = new TreeNode(1); + + std::cout << Solution::good_nodes(root); + + return 0; +}