-
Notifications
You must be signed in to change notification settings - Fork 1
/
EvenOddTree.java
49 lines (42 loc) · 1.33 KB
/
EvenOddTree.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
// https://leetcode.com/problems/even-odd-tree/
public class EvenOddTree {
private final TreeNode input;
public EvenOddTree(TreeNode input) {
this.input = input;
}
public boolean solution() {
Queue<TreeNode> nodes = new LinkedList<>();
nodes.add(input);
int level = 0;
while (!nodes.isEmpty()) {
int size = nodes.size();
int prev = -1;
for (int i = 0; i < size; i++) {
TreeNode node = nodes.poll();
int val = node.val;
if (level % 2 == 0) {
if (val % 2 == 0 || (prev != -1 && prev >= val)) {
return false;
}
} else {
if (val % 2 != 0 || (prev != -1 && prev <= val)) {
return false;
}
}
if (node.left != null) {
nodes.add(node.left);
}
if (node.right != null) {
nodes.add(node.right);
}
prev = val;
}
level++;
}
return true;
}
}