From 994db141aa831866a5551d7c01c5d676252b9876 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Wed, 3 May 2023 20:06:39 -0500 Subject: [PATCH] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 39 ++++++++++++++++------- 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index ed2c683d..6235ad21 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -1761,22 +1761,37 @@ public: python代码: ```python +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right class Solution: def largestValues(self, root: TreeNode) -> List[int]: - if root is None: + if not root: return [] - queue = [root] - out_list = [] + + result = [] + queue = collections.deque([root]) + while queue: - length = len(queue) - in_list = [] - for _ in range(length): - curnode = queue.pop(0) - in_list.append(curnode.val) - if curnode.left: queue.append(curnode.left) - if curnode.right: queue.append(curnode.right) - out_list.append(max(in_list)) - return out_list + level_size = len(queue) + max_val = float('-inf') + + for _ in range(level_size): + node = queue.popleft() + max_val = max(max_val, node.val) + + if node.left: + queue.append(node.left) + + if node.right: + queue.append(node.right) + + result.append(max_val) + + return result ``` java代码: