[LeetCode] Even Odd Tree

1609. Even Odd Tree

A binary tree is named Even-Odd if it meets the following conditions:

  • The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
  • For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
  • For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).

Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* 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) {}
* };
*/
class Solution {
vector<int> order;
bool helper(TreeNode* node, int level) {
if(!node) return true;
if((level & 1) and (node->val & 1)) return false;
if(!(level & 1) and (!(node->val & 1))) return false;
if(order.size() == level) order.push_back(node->val + (level & 1 ? 1 : -1));
if(level & 1) {
if(order[level] <= node->val) return false;
} else {
if(order[level] >= node->val) return false;
}
order[level] = node->val;
return helper(node->left, level + 1) and helper(node->right, level + 1);
}
public:
bool isEvenOddTree(TreeNode* root) {
return helper(root, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/03/PS/LeetCode/even-odd-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.