一. 题目
-
题目
-
示例
二. 方法一: 层次遍历
-
解题思路
层次遍历, 将同一层的所有元素通过next指针连起来即可 -
解题代码
def connect(self, root: 'Node') -> 'Node': if not root: return root # res 用于存储需要依次遍历的元素 res = [root] while res: # 获取同一层的元素个数 size = len(res) # 遍历同一层的元素 for i in range(size): # 弹出队首的元素 ele = res.pop(0) # 前size个元素是同一层的 if i < size - 1: ele.next = res[0] # 如果弹出来的元素有左右子节点, 则插入到队尾 if ele.left: res.append(ele.left) if ele.right: res.append(ele.right) return root
-
分析
时间复杂度: O(n)
空间复杂度: O(n)
三. 方法二
-
解题思路
- 因为二叉树是完美二叉树, 所以有左节点, 则必有右节点
- 如果两节点有公共父节点, 则直接让左节点的next指针, 指向右节点
- 如果当前节点的next指针不为空, 则需要将其右节点指向next的左节点
- 然后再对其左右直接点进行上述操作
-
解题代码
def connect(self, root: 'Node') -> 'Node': if not root: return root if root.left: root.left.next = root.right if root.next: root.right.next = root.next.left # else: # root.right.next = None self.connect(root.left) self.connect(root.right) return root
-
分析
时间复杂度: O(n)
空间复杂度: O(1)