【 Even Odd Tree】leetcode 解题 2/29 (tree)

题目连结

code 连结

解题

使用bfs去查找每个level

依据规则:
如果这层是基数个,里面的值都要是基数,且递减
反之为偶数个,里面的值都要是偶数,且递增

就这样一层一层查找,直到找不到子节点

code (java)

/** * 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) {        // create a new queue        Queue<TreeNode> q = new LinkedList<TreeNode>();        // push back root        q.offer(root);        //set begin level is 1        int level = 1;        // while tree have children        while(!q.isEmpty()){                        int qsize = q.size();            // if odd in || if even de            int pre = level % 2 == 1 ? -1 : Integer.MAX_VALUE;            while(qsize-- > 0){                // get the top tree                TreeNode node = q.poll();                // the rule                 if(level % 2 == 0){                    if(node.val % 2 == 1 || pre <= node.val) return false;                }                else{                    if(node.val % 2 == 0 || pre >= node.val) return false;                }                // to cmp with next                pre = node.val;                // have chidren ? add : nothing                if(node.left != null) q.offer(node.left);                if(node.right != null) q.offer(node.right);            }            // level up            level++;        }        //follow all rule         return true;    }}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章