Leetcode Java_二叉樹

Yake1965 2022-01-07 20:10:51 阅读数:205

leetcode java_ java 二叉

二叉樹

1609. 奇偶樹

Leetcode

class Solution {

public boolean isEvenOddTree(TreeNode root) {

Deque<TreeNode> q = new LinkedList<>();
q.offer(root);
boolean even = true;
while(!q.isEmpty()){

int size = q.size(), pre = (even) ? 0 : 1000000;
// for(int i = 0; i < q.size(); i++){ // 不能直接使用 q.size() 
while(size-- > 0){

TreeNode node = q.poll();
int x = node.val;
if(even){

// 偶數下標,x 是偶數或遞减
if(x % 2 == 0 || pre >= x) return false;
}
else{

// 奇數下標,x 是奇數或遞增 
if(x % 2 == 1 || pre <= x) return false;
}
pre = x;
if(node.left != null) q.offer(node.left);
if(node.right != null) q.offer(node.right);
}
even = !even;
}
return true;
}
}
版权声明:本文为[Yake1965]所创,转载请带上原文链接,感谢。 https://gsmany.com/2022/01/202201072010507840.html