mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-13 18:12:16 +00:00
添加Go语言题解
This commit is contained in:
@@ -426,6 +426,34 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
Go Code:
|
||||
|
||||
```go
|
||||
func levelOrder(root *TreeNode) [][]int {
|
||||
res := [][]int{}
|
||||
if root == nil {
|
||||
return res
|
||||
}
|
||||
// 初始化队列时,记得把root节点加进去。
|
||||
que := []*TreeNode{root}
|
||||
for len(que) != 0 {
|
||||
t := []int{}
|
||||
// 这里一定要先求出来que的长度,因为在迭代的过程中,que的长度是变化的。
|
||||
l := len(que)
|
||||
for i := 0; i < l; i++ {
|
||||
temp := que[0]
|
||||
que = que[1:]
|
||||
// 子节点不为空,就入队
|
||||
if temp.Left != nil { que = append(que, temp.Left) }
|
||||
if temp.Right != nil { que = append(que, temp.Right) }
|
||||
t = append(t, temp.Val)
|
||||
}
|
||||
res = append(res, t)
|
||||
}
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
时间复杂度:O(n) 空间复杂度:O(n)
|
||||
|
||||
大家如果吃透了二叉树的层序遍历的话,可以顺手把下面几道题目解决掉,思路一致,甚至都不用拐弯
|
||||
|
Reference in New Issue
Block a user