2022-8-10 剑指offer-队列
给定一棵二叉树的根节点 root
,请找出该二叉树中每一层的最大值。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public List<Integer> largestValues(TreeNode root) { 18 Queue<TreeNode> queue=new LinkedList<>(); 19 List<Integer> ans=new ArrayList<>(); 20 if (root==null) return ans; 21 queue.offer(root); 22 while (!queue.isEmpty()){ 23 int size=queue.size(); 24 int max=Integer.MIN_VALUE; 25 for (int i=0;i<size;i++){ 26 TreeNode node=queue.poll(); 27 if (node.left!=null) queue.offer(node.left); 28 if (node.right!=null) queue.offer(node.right); 29 max=Math.max(max,node.val); 30 } 31 ans.add(max); 32 } 33 return ans; 34 } 35 }
思路:二叉树的层序遍历,用队列实现。