提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、力扣1161. 最大层内元素和
- 二、力扣1302. 层数最深叶子节点的和
- 三、力扣1609. 奇偶树
前言
有些二叉树的特殊技巧需要用层序遍历的方式来做,比如下面列举的几道题。这类问题你当特殊题型记住就行了,不会有太多变体的。
一、力扣1161. 最大层内元素和
/*** 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 int maxLevelSum(TreeNode root) {int len = Integer.MAX_VALUE;int sum = Integer.MIN_VALUE;int depth = 1;Deque<TreeNode> deq = new ArrayDeque<>();deq.offerLast(root);while(!deq.isEmpty()){int count = 0;int size = deq.size();for(int i = 0; i < size; i ++){TreeNode cur = deq.pollFirst();count += cur.val;if(cur.left != null){deq.offerLast(cur.left);}if(cur.right != null){deq.offerLast(cur.right);}}if(count > sum){sum = count;len = depth;}depth ++;}return len;}
}
二、力扣1302. 层数最深叶子节点的和
/*** 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 int deepestLeavesSum(TreeNode root) {int sum = 0;Deque<TreeNode> deq = new ArrayDeque<>();deq.offerLast(root);while(!deq.isEmpty()){int size = deq.size();int count = 0;for(int i = 0; i < size; i ++){TreeNode cur = deq.pollFirst();if(cur.left != null){deq.offerLast(cur.left);}if(cur.right != null){deq.offerLast(cur.right);}if(cur.left == null && cur.right == null){count += cur.val;}}sum = count;}return sum;}
}
三、力扣1609. 奇偶树
/*** 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) {if(root.val % 2 == 0){return false;}Deque<TreeNode> deq = new ArrayDeque<>();deq.offerLast(root);int depth = 0;while(!deq.isEmpty()){TreeNode pre = null;int size = deq.size();for(int i = 0; i < size; i ++){TreeNode cur = deq.pollFirst();if(cur.left != null){deq.offerLast(cur.left);}if(cur.right != null){deq.offerLast(cur.right);}if(depth % 2 == 0 && cur.val % 2 == 0){return false;}if(depth % 2 == 1 && cur.val % 2 == 1){return false;}if(pre != null){if(depth % 2 == 0){if(pre.val >= cur.val){return false;}}else{if(pre.val <= cur.val){return false;}}}pre = cur;}depth ++;}return true;}
}