1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00

cpp: add «1609. Even Odd Tree»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-02-29 23:28:54 +01:00
parent 510ad47987
commit 981c119d36
Signed by: mfocko
GPG key ID: 7C47D46246790496

49
cpp/even-odd-tree.cpp Normal file
View file

@ -0,0 +1,49 @@
#include <unordered_map>
#ifdef _MF_TEST
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right)
: val(x), left(left), right(right) {}
};
#endif
class Solution {
auto isEvenOddTree(std::unordered_map<int, int> &view, int level,
TreeNode *root) const -> bool {
if (root == nullptr) {
return true;
}
// check the parity
if (level % 2 == root->val % 2) {
return false;
}
// check the ordering
auto &last = view[level];
if (last != 0 && level % 2 == 0 && root->val <= last) {
return false;
} else if (last != 0 && level % 2 != 0 && root->val >= last) {
return false;
}
last = root->val;
if (!isEvenOddTree(view, level + 1, root->left) ||
!isEvenOddTree(view, level + 1, root->right)) {
return false;
}
return true;
}
public:
bool isEvenOddTree(TreeNode *root) const {
std::unordered_map<int, int> leftview;
return isEvenOddTree(leftview, 0, root);
}
};