Sponsored
Sponsored
This approach employs a breadth-first search (BFS) to traverse the binary tree level by level. We maintain a queue to keep track of the nodes at each level, examining their values to ensure compliance with the Even-Odd criteria:
Time Complexity: O(N), where N is the number of nodes, as each node is inspected once.
Space Complexity: O(M), where M is the maximum number of nodes at any level in the tree (width of the tree), due to the BFS queue.
1class TreeNode {
2 constructor(val, left = null, right = null) {
3 this.val = val;
4 this.left = left;
5 this.right = right;
6 }
7}
8
9function isEvenOddTree(root) {
10 if (!root) return false;
11
12 let queue = [root];
13 let level = 0;
14
15 while (queue.length > 0) {
16 let levelLength = queue.length;
17 let prev = null;
18
19 for (let i = 0; i < levelLength; i++) {
20 let node = queue.shift();
21
22 if (level % 2 === 0) {
23 if (node.val % 2 === 0 || (prev !== null && node.val <= prev)) {
24 return false;
25 }
26 } else {
27 if (node.val % 2 !== 0 || (prev !== null && node.val >= prev)) {
28 return false;
29 }
30 }
31
32 prev = node.val;
33
34 if (node.left) queue.push(node.left);
35 if (node.right) queue.push(node.right);
36 }
37
38 level++;
39 }
40
41 return true;
42}
The JavaScript solution processes the tree similarly using a queue (BFS), checking odd/even conditions per level and comparing current node values to the previously processed node at the current level.
This approach applies a depth-first search (DFS) method, maintaining level information to confirm constraints. We use recursion to explore the tree, while an array stores the last value seen on each level to validate order constraints.
Time Complexity: O(N), with N being the number of nodes.
Space Complexity: O(H), where H is the height of the tree, accounting for recursion stack and the array storing last values at each level.
1#include <vector>
2#include <algorithm>
3using namespace std;
4
5struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
bool isValid(TreeNode* node, int level, vector<int>& lastVals) {
if (!node) return true;
if (lastVals.size() <= level) {
lastVals.push_back(level % 2 == 0 ? INT_MIN : INT_MAX);
}
if ((level % 2 == 0 && (node->val % 2 == 0 || node->val <= lastVals[level])) ||
(level % 2 == 1 && (node->val % 2 == 1 || node->val >= lastVals[level]))) {
return false;
}
lastVals[level] = node->val;
return isValid(node->left, level + 1, lastVals) && isValid(node->right, level + 1, lastVals);
}
bool isEvenOddTree(TreeNode* root) {
vector<int> lastVals;
return isValid(root, 0, lastVals);
}
};
In the C++ solution, we use a recursive function to perform DFS while maintaining the last meaningful value for level validation in an array. This array ensures all nodes at each level meet the Even-Odd Tree constraints.