LC.P1609[奇偶树] 方法一:BFS1234567891011121314151617181920212223242526272829303132333435363738394041/** * 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) { Deque<TreeNode> queue = new ArrayDeque<>(); queue.offer(root); int depth = 0; while (!queue.isEmpty()) { int size = queue.size(); List<Integer> list = new ArrayList<>(); while (size-- > 0) { TreeNode cur = queue.poll(); if (depth % 2 == 0) { if (cur.val % 2 == 0) return false; if (!list.isEmpty() && list.get(list.size() - 1) >= cur.val) return false; } else { if (cur.val % 2 == 1) return false; if (!list.isEmpty() && list.get(list.size() - 1) <= cur.val) return false; } list.add(cur.val); if (cur.left != null) queue.offer(cur.left); if (cur.right != null) queue.offer(cur.right); } ++depth; } return true; }} 时间复杂度:$O(n)$ 空间复杂度:$O(n)$ 方法二:优化123456789101112131415161718192021222324252627282930313233343536/** * 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) { Deque<TreeNode> queue = new ArrayDeque<>(); queue.offer(root); boolean flag = true; while (!queue.isEmpty()) { int size = queue.size(), prev = flag ? 0 : Integer.MAX_VALUE; while (size-- > 0) { TreeNode node = queue.poll(); int cur = node.val; if (flag && (cur % 2 == 0 || cur <= prev)) return false; if (!flag && (cur % 2 != 0 || cur >= prev)) return false; prev = cur; if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } flag = !flag; } return true; }} 时间复杂度:$O(n)$ 空间复杂度:$O(n)$ 方法三:DFS123456789101112131415161718192021222324252627282930313233/** * 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 { Map<Integer, Integer> map = new HashMap<>(); public boolean isEvenOddTree(TreeNode root) { return dfs(root, 0); } private boolean dfs(TreeNode root, int idx) { boolean flag = idx % 2 == 0; int prev = map.getOrDefault(idx, flag ? 0 : Integer.MAX_VALUE), 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; }} 时间复杂度:$O(n)$ 空间复杂度:$O(n)$