思路:层次遍历二叉树+每层串联起来
"""
# 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':
'''
思路:层次遍历,在每一层用一个Node节点串起来
'''
if not root:
return root
q = [root]
while q:
demmy_node = Node()
leng = len(q)
for _ in range(leng):
node = q.pop(0)
demmy_node.next = node
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
demmy_node = node
return root
|