1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00
LeetCode/cpp/even-odd-tree.cpp

50 lines
1.3 KiB
C++
Raw Normal View History

#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);
}
};