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