Skip to content

Commit

Permalink
Added Count Complete Tree Nodes logNxlogN
Browse files Browse the repository at this point in the history
  • Loading branch information
Ace-Krypton committed Sep 20, 2023
1 parent 5be8731 commit 2718071
Showing 1 changed file with 31 additions and 5 deletions.
36 changes: 31 additions & 5 deletions Easy/CountCompleteTreeNodes/include/solution.hpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#pragma once

#include <cmath>
#include <vector>
#include <iostream>
#include <algorithm>
Expand All @@ -16,16 +17,41 @@ struct TreeNode {
class Solution {
public:
static auto count_nodes(TreeNode *root) -> int32_t {
if (!root) return 0;

std::function<int32_t(TreeNode*)> lh =
[&](TreeNode *root) -> int32_t {
if (!root) return 0;
return lh(root->left) + 1;
};

std::function<int32_t(TreeNode*)> rh =
[&](TreeNode *root) -> int32_t {
if (!root) return 0;
return rh(root->right) + 1;
};

const int32_t left_height = lh(root);
const int32_t right_height = rh(root);

if (left_height == right_height) {
return std::pow(2, left_height) - 1;
}

return count_nodes(root->left) + count_nodes(root->right) + 1;
}

[[maybe_unused]] static auto count_nodes_tle(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);
};
if (root == nullptr) return;
++count;
preorder(root->left);
preorder(root->right);
};

preorder(root);
return count;
Expand Down

0 comments on commit 2718071

Please sign in to comment.