代码仓库:Github | Leetcode solutions @doubleZ0108 from Peking University.
- 解法1(T22% S5%):这个任务是第一次看很新奇,但仔细看了示意图这不就是树的层次遍历问题吗!直接用队列层次遍历树,弹出头节点作为当前节点,如果当前队列中的头元素跟改元素是同一层级的,那该节点的next就是当前队列的头
- 或者也可以不通过层级控制,因为是完美二叉树所以每层都一定是 2 n 2^n 2n个节点,也可以根据这个作为边界条件
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
if not root or (not root.left and not root.right): return root
queue = [(root, 0)]
while queue:
node, level = queue.pop(0)
if queue and queue[0][1] == level:
node.next = queue[0][0]
if node.left:
queue.append((node.left, level+1))
if node.right:
queue.append((node.right, level+1))
return root
该文章介绍了一种使用队列进行层次遍历的方法来解决二叉树问题。在完美二叉树中,通过层次遍历并利用层级信息,将相邻节点连接起来。代码实现中,如果队列不为空并且头元素在同一层级,就将头节点设为当前节点的next。
1301

被折叠的 条评论
为什么被折叠?



