BFS:
层序遍历,左指向右即可,注意最后一个指向nil
/**
* Definition for a Node.
* type Node struct {
* Val int
* Left *Node
* Right *Node
* Next *Node
* }
*/
func connect(root *Node) *Node {
if root == nil {
return root
}
qu := []*Node{root}
for len(qu) > 0 {
q := []*Node{}
n := len(qu) - 1
for i := 0; i < n; i++ {
qu[i].Next = qu[i+1]
if qu[i].Left != nil {
q = append(q, qu[i].Left)
}
if qu[i].Right != nil {
q = append(q, qu[i].Right)
}
}
qu[n].Next = nil
if qu[n].Left != nil {
q = append(q, qu[n].Left)
}
if qu[n].Right != nil {
q = append(q, qu[n].Right)
}
qu = q
}
return root
}
DFS:
- 常数级空间解决问题
- 没有使用队列模拟bfs
func connect(root *Node) *Node {
if root == nil {
return root
}
// 每次循环从该层的最左侧节点开始
for leftmost := root; leftmost.Left != nil; leftmost = leftmost.Left {
// 通过 Next 遍历这一层节点,为下一层的节点更新 Next 指针
for node := leftmost; node != nil; node = node.Next {
// 左节点指向右节点
node.Left.Next = node.Right
// 右节点指向下一个左节点
if node.Next != nil {
node.Right.Next = node.Next.Left
}
}
}
// 返回根节点
return root
}