Skip to content

Commit 03c63e7

Browse files
authored
Merge pull request #3562 from aadil42/patch-98
Create 1609-even-odd-tree.js
2 parents 04f36d2 + 3b367a2 commit 03c63e7

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

javascript/1609-even-odd-tree.js

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
10+
/**
11+
* Level Order Traversal | BFS
12+
* Time O(n) | Space O(n)
13+
* https://leetcode.com/problems/even-odd-tree
14+
* @param {TreeNode} root
15+
* @return {boolean}
16+
*/
17+
var isEvenOddTree = function(root) {
18+
19+
// helper function
20+
const isStricklyIncreasingAndOdd = (arr) => {
21+
22+
for (let i = 0; i < arr.length; i++) {
23+
const currElement = arr[i];
24+
const nextElement = (arr[i+1] !== undefined && arr[i+1]) || Infinity;
25+
if (currElement >= nextElement || currElement%2 === 0) return false;
26+
}
27+
28+
return true;
29+
}
30+
31+
// helper function
32+
const isStricklyDecreasingAndEven = (arr) => {
33+
34+
for (let i = 0; i < arr.length; i++) {
35+
const currElement = arr[i];
36+
const nextElement = (arr[i+1] !== undefined && arr[i+1]) || -Infinity;
37+
if (currElement <= nextElement || currElement%2 === 1) return false;
38+
}
39+
40+
return true;
41+
}
42+
43+
const q = new Queue();
44+
q.enqueue([root, 0]);
45+
46+
while (!q.isEmpty()) {
47+
const size = q.size();
48+
49+
const levelArr = [];
50+
const level = q.front()[1];
51+
52+
for (let i = 0; i < size; i++) {
53+
54+
const element = q.dequeue();
55+
const node = element[0];
56+
levelArr.push(node.val);
57+
58+
node.left && q.enqueue([node.left, level+1]);
59+
node.right && q.enqueue([node.right, level+1]);
60+
}
61+
62+
if (level%2 === 0 && !isStricklyIncreasingAndOdd(levelArr)) return false;
63+
if (level%2 === 1 && !isStricklyDecreasingAndEven(levelArr)) return false;
64+
}
65+
66+
return true;
67+
};

0 commit comments

Comments
 (0)