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:
@ -2381,21 +2381,41 @@ python代码:
|
||||
|
||||
```python
|
||||
# 层序遍历解法
|
||||
"""
|
||||
# Definition for a Node.
|
||||
class Node:
|
||||
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
|
||||
self.val = val
|
||||
self.left = left
|
||||
self.right = right
|
||||
self.next = next
|
||||
"""
|
||||
|
||||
class Solution:
|
||||
def connect(self, root: 'Node') -> 'Node':
|
||||
if not root:
|
||||
return None
|
||||
queue = [root]
|
||||
while queue: # 遍历每一层
|
||||
length = len(queue)
|
||||
tail = None # 每一层维护一个尾节点
|
||||
for i in range(length): # 遍历当前层
|
||||
curnode = queue.pop(0)
|
||||
if tail:
|
||||
tail.next = curnode # 让尾节点指向当前节点
|
||||
tail = curnode # 让当前节点成为尾节点
|
||||
if curnode.left : queue.append(curnode.left)
|
||||
if curnode.right: queue.append(curnode.right)
|
||||
return root
|
||||
|
||||
queue = collections.deque([root])
|
||||
|
||||
while queue:
|
||||
level_size = len(queue)
|
||||
prev = None
|
||||
|
||||
for i in range(level_size):
|
||||
node = queue.popleft()
|
||||
|
||||
if prev:
|
||||
prev.next = node
|
||||
|
||||
prev = node
|
||||
|
||||
if node.left:
|
||||
queue.append(node.left)
|
||||
|
||||
if node.right:
|
||||
queue.append(node.right)
|
||||
|
||||
return root
|
||||
|
||||
```
|
||||
|
Reference in New Issue
Block a user