cpp: add «1609. Even Odd Tree»
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
510ad47987
commit
981c119d36
1 changed files with 49 additions and 0 deletions
49
cpp/even-odd-tree.cpp
Normal file
49
cpp/even-odd-tree.cpp
Normal 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);
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue