优化二叉树层序遍历116和117题的go方法

This commit is contained in:
marspere
2022-08-19 10:50:33 +08:00
parent b7e4c6901f
commit 10734b6f20

View File

@ -1891,13 +1891,12 @@ go:
*/ */
func connect(root *Node) *Node { func connect(root *Node) *Node {
res:=[][]*Node{}
if root == nil { //防止为空 if root == nil { //防止为空
return root return root
} }
queue := list.New() queue := list.New()
queue.PushBack(root) queue.PushBack(root)
var tmpArr []*Node tmpArr := make([]*Node, 0)
for queue.Len() > 0 { for queue.Len() > 0 {
length := queue.Len() //保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数) length := queue.Len() //保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数)
for i := 0; i < length; i++ { for i := 0; i < length; i++ {
@ -1910,17 +1909,17 @@ func connect(root *Node) *Node {
} }
tmpArr = append(tmpArr, node) //将值加入本层切片中 tmpArr = append(tmpArr, node) //将值加入本层切片中
} }
res=append(res,tmpArr)//放入结果集 if len(tmpArr) > 1 {
tmpArr=[]*Node{}//清空层的数据
}
// 遍历每层元素,指定next // 遍历每层元素,指定next
for i:=0;i<len(res);i++{ for i := 0; i < len(tmpArr)-1; i++ {
for j:=0;j<len(res[i])-1;j++{ tmpArr[i].Next = tmpArr[i+1]
res[i][j].Next=res[i][j+1]
} }
} }
tmpArr = []*Node{} //清空层的数据
}
return root return root
} }
``` ```
Swift Swift
@ -2172,13 +2171,12 @@ go:
*/ */
func connect(root *Node) *Node { func connect(root *Node) *Node {
res:=[][]*Node{}
if root == nil { //防止为空 if root == nil { //防止为空
return root return root
} }
queue := list.New() queue := list.New()
queue.PushBack(root) queue.PushBack(root)
var tmpArr []*Node tmpArr := make([]*Node, 0)
for queue.Len() > 0 { for queue.Len() > 0 {
length := queue.Len() //保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数) length := queue.Len() //保存当前层的长度,然后处理当前层(十分重要,防止添加下层元素影响判断层中元素的个数)
for i := 0; i < length; i++ { for i := 0; i < length; i++ {
@ -2191,15 +2189,14 @@ func connect(root *Node) *Node {
} }
tmpArr = append(tmpArr, node) //将值加入本层切片中 tmpArr = append(tmpArr, node) //将值加入本层切片中
} }
res=append(res,tmpArr)//放入结果集 if len(tmpArr) > 1 {
tmpArr=[]*Node{}//清空层的数据
}
// 遍历每层元素,指定next // 遍历每层元素,指定next
for i:=0;i<len(res);i++{ for i := 0; i < len(tmpArr)-1; i++ {
for j:=0;j<len(res[i])-1;j++{ tmpArr[i].Next = tmpArr[i+1]
res[i][j].Next=res[i][j+1]
} }
} }
tmpArr = []*Node{} //清空层的数据
}
return root return root
} }
``` ```