mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
102.二叉树的层序遍历增加Go使用切片解法
This commit is contained in:
@ -265,7 +265,7 @@ func levelOrder(root *TreeNode) [][]int {
|
|||||||
|
|
||||||
```go
|
```go
|
||||||
/**
|
/**
|
||||||
102. 二叉树的层序遍历
|
102. 二叉树的层序遍历 使用container包
|
||||||
*/
|
*/
|
||||||
func levelOrder(root *TreeNode) [][]int {
|
func levelOrder(root *TreeNode) [][]int {
|
||||||
res := [][]int{}
|
res := [][]int{}
|
||||||
@ -296,6 +296,35 @@ func levelOrder(root *TreeNode) [][]int {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
102. 二叉树的层序遍历 使用切片
|
||||||
|
*/
|
||||||
|
func levelOrder(root *TreeNode) [][]int {
|
||||||
|
res := make([][]int, 0)
|
||||||
|
if root == nil {
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
queue := make([]*TreeNode, 0)
|
||||||
|
queue = append(queue, root)
|
||||||
|
for len(queue) > 0 {
|
||||||
|
size := len(queue)
|
||||||
|
level := make([]int, 0)
|
||||||
|
for i := 0; i < size; i++ {
|
||||||
|
node := queue[0]
|
||||||
|
queue = queue[1:]
|
||||||
|
level = append(level, node.Val)
|
||||||
|
if node.Left != nil {
|
||||||
|
queue = append(queue, node.Left)
|
||||||
|
}
|
||||||
|
if node.Right != nil {
|
||||||
|
queue = append(queue, node.Right)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res = append(res, level)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
102. 二叉树的层序遍历:使用切片模拟队列,易理解
|
102. 二叉树的层序遍历:使用切片模拟队列,易理解
|
||||||
*/
|
*/
|
||||||
|
Reference in New Issue
Block a user