mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0102.二叉树的层序遍历.md
This commit is contained in:
@ -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代码:
|
||||
|
Reference in New Issue
Block a user