Skip to content

Commit

Permalink
Added Count Good Nodes in Binary Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Oct 5, 2023
1 parent 709fedc commit 864f52c
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
36 changes: 36 additions & 0 deletions Medium/CountGoodNodesInBinaryTree/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#pragma once

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

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<void(TreeNode*, int32_t)> 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;
};
14 changes: 14 additions & 0 deletions Medium/CountGoodNodesInBinaryTree/tests/test.cpp
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit 864f52c

Please sign in to comment.