Skip to content

Commit

Permalink
Added Count Complete Tree Nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 20, 2023
1 parent a501419 commit 5be8731
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -821,4 +821,15 @@ add_executable(PathSum
target_link_libraries(
PathSum
GTest::gtest_main
)

# Count Complete Tree Nodes
add_executable(CountCompleteTreeNodes
Easy/CountCompleteTreeNodes/include/solution.hpp
Easy/CountCompleteTreeNodes/tests/test.cpp
)

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

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

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

class Solution {
public:
static auto count_nodes(TreeNode *root) -> int32_t {
if (root == nullptr) return 0;

int32_t count = 0;
std::function<void(TreeNode*)> preorder =
[&](TreeNode *root) -> void {
if (root == nullptr) return;
++count;
preorder(root->left);
preorder(root->right);
};

preorder(root);
return count;
}
};
14 changes: 14 additions & 0 deletions Easy/CountCompleteTreeNodes/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(1);
root->left = new TreeNode(2);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right = new TreeNode(3);
root->right->left = new TreeNode(6);

std::cout << Solution::count_nodes(root);

return 0;
}

0 comments on commit 5be8731

Please sign in to comment.