-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added Count Good Nodes in Binary Tree
- Loading branch information
1 parent
709fedc
commit 864f52c
Showing
3 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |