BFS:
class Solution {
public boolean isEvenOddTree(TreeNode root) {
Deque<TreeNode> bf= new ArrayDeque<>();//设置队列
boolean flag = true;//判断是否为偶数
bf.addLast(root);//加入根节点
while (!d.isEmpty()) {
int size = bf.size(), prev = flag ? 0 : 0x3f3f3f3f;//判断哨兵值,判断最大和最小
while (size-- > 0) {
TreeNode node = bf.pollFirst();//取出头节点
int value = node.val;//值是唯一的
if (flag && (value% 2 == 0 || value <= prev)) return false;
if (!flag && (value % 2 != 0 || value>= prev)) return false;//与最初那个最大或者最小值进行比较
prev = value;//要取那个唯一值,作为当前行头节点
if (node.left != null) bf.addLast(node.left);
if (node.right != null) bf.addLast(node.right);
}
flag = !flag;
}
return true;
}
}
class Solution {
Map<Integer, Integer> map = new HashMap<>();
public boolean isEvenOddTree(TreeNode root) {
return dfs(root, 0);
}
boolean dfs(TreeNode root, int idx) {
boolean flag = idx % 2 == 0;//判断为偶数
int prev = map.getOrDefault(idx, flag ? 0 : 0x3f3f3f3f), cur = root.val;
if (flag && (cur % 2 == 0 || cur <= prev)) return false;
if (!flag && (cur % 2 != 0 || cur >= prev)) return false;
map.put(idx, root.val);
if (root.left != null && !dfs(root.left, idx + 1)) return false;
if (root.right != null && !dfs(root.right, idx + 1)) return false;
return true;
}
}