描述
该题来自于力扣第116题
分析
最简单的思路就是层次遍历,然后每层连接就好了。这里介绍另一种方法。
树类问题一般是大问题化解小问题,该题也是如此,但是稍微有些不同,首先这么看,对于某个结点root
,首先连接左右节点,即root.left.next = root.right
,如果用这种思路递归的话,会少一些连线,如下图所示:
1
2
3
4
5 1
/ \
2 ----> 3
/ \ / \
4 -> 5 6 -> 7
1
作为root
结点,将2,3
连接;2
作为root
结点,将4,5
连接3
作为root
结点,将6,7
连接
可以看到完成后,5
和6
之间少一个连线,这时回到以2
作为root
结点的情况,因为2
有next
,若将root.right.next = root.next.left
,不就将5,6
连起来了嘛。
所以递归时,做两件事:
1. root.left.next = root.right
2. root.right.next = root.next.left
再递归左右子树就行。
代码
1 | class Solution: |