From b79f3e0fb75ceefdc7b7db1b9f60fd53e3c3fee0 Mon Sep 17 00:00:00 2001 From: wutianjue Date: Mon, 7 Mar 2022 14:38:03 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E6=AF=8F=E4=B8=AA=E6=A0=91?= =?UTF-8?q?=E8=A1=8C=E4=B8=AD=E6=89=BE=E6=9C=80=E5=A4=A7=E5=80=BCJava?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 34 +++++++++++------------ 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 74485848..42380b15 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1300,23 +1300,23 @@ java代码: ```java class Solution { public List largestValues(TreeNode root) { - List retVal = new ArrayList(); - Queue tmpQueue = new LinkedList(); - if (root != null) tmpQueue.add(root); - - while (tmpQueue.size() != 0){ - int size = tmpQueue.size(); - List lvlVals = new ArrayList(); - for (int index = 0; index < size; index++){ - TreeNode node = tmpQueue.poll(); - lvlVals.add(node.val); - if (node.left != null) tmpQueue.add(node.left); - if (node.right != null) tmpQueue.add(node.right); - } - retVal.add(Collections.max(lvlVals)); - } - - return retVal; + if(root == null){ + return Collections.emptyList(); + } + List result = new ArrayList(); + Queue queue = new LinkedList(); + queue.offer(root); + while(!queue.isEmpty()){ + int max = Integer.MIN_VALUE; + for(int i = queue.size(); i > 0; i--){ + TreeNode node = queue.poll(); + max = Math.max(max, node.val); + if(node.left != null) queue.offer(node.left); + if(node.right != null) queue.offer(node.right); + } + result.add(max); + } + return result; } } ```