mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
Update 0102.二叉树的层序遍历.md
This commit is contained in:
@ -1761,22 +1761,37 @@ public:
|
|||||||
python代码:
|
python代码:
|
||||||
|
|
||||||
```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:
|
class Solution:
|
||||||
def largestValues(self, root: TreeNode) -> List[int]:
|
def largestValues(self, root: TreeNode) -> List[int]:
|
||||||
if root is None:
|
if not root:
|
||||||
return []
|
return []
|
||||||
queue = [root]
|
|
||||||
out_list = []
|
result = []
|
||||||
|
queue = collections.deque([root])
|
||||||
|
|
||||||
while queue:
|
while queue:
|
||||||
length = len(queue)
|
level_size = len(queue)
|
||||||
in_list = []
|
max_val = float('-inf')
|
||||||
for _ in range(length):
|
|
||||||
curnode = queue.pop(0)
|
for _ in range(level_size):
|
||||||
in_list.append(curnode.val)
|
node = queue.popleft()
|
||||||
if curnode.left: queue.append(curnode.left)
|
max_val = max(max_val, node.val)
|
||||||
if curnode.right: queue.append(curnode.right)
|
|
||||||
out_list.append(max(in_list))
|
if node.left:
|
||||||
return out_list
|
queue.append(node.left)
|
||||||
|
|
||||||
|
if node.right:
|
||||||
|
queue.append(node.right)
|
||||||
|
|
||||||
|
result.append(max_val)
|
||||||
|
|
||||||
|
return result
|
||||||
```
|
```
|
||||||
|
|
||||||
java代码:
|
java代码:
|
||||||
|
Reference in New Issue
Block a user