其他分享
首页 > 其他分享> > LeetCode 1609 Even Odd Tree (bfs)

LeetCode 1609 Even Odd Tree (bfs)

作者:互联网

A binary tree is named Even-Odd if it meets the following conditions:

Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.

Example 1:

Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
Output: true
Explanation: The node values on each level are:
Level 0: [1]
Level 1: [10,4]
Level 2: [3,7,9]
Level 3: [12,8,6,2]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.

Example 2:

Input: root = [5,4,2,3,3,7]
Output: false
Explanation: The node values on each level are:
Level 0: [5]
Level 1: [4,2]
Level 2: [3,3,7]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.

Example 3:

Input: root = [5,9,1,3,5,7]
Output: false
Explanation: Node values in the level 1 should be even integers.

Constraints:

题目链接:https://leetcode.com/problems/even-odd-tree/

题目大意:问树满不满足奇数层全偶且严格递减,偶数层全奇且严格递增

题目分析:层次遍历,按条件判断即可

15ms,时间击败71.4%

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isEvenOddTree(TreeNode root) {
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        int h = 0;
        while (!q.isEmpty()) {
            int sz = q.size(), ma = Integer.MIN_VALUE, mi = Integer.MAX_VALUE;
            for (int i = 0; i < sz; i++) {
                TreeNode cur = q.poll();
                if (h % 2 == cur.val % 2) {
                    return false;
                }
                if (h % 2 == 0) {
                    if (cur.val <= ma) {
                        return false;
                    } 
                    ma = cur.val;
                } else {
                    if (cur.val >= mi) {
                        return false;
                    } 
                    mi = cur.val;
                }
                if (cur.left != null) {
                    q.offer(cur.left);
                }
                if (cur.right != null) {
                    q.offer(cur.right);
                }
            }
            h++;
        }
        return true;
    }
}

标签:1609,Even,right,TreeNode,cur,val,level,tree,Tree
来源: https://blog.csdn.net/Tc_To_Top/article/details/123130252