From 1cf800b89f3785d2cfd7b0dc040da4f294e0682d Mon Sep 17 00:00:00 2001 From: markwang Date: Tue, 18 Jun 2024 17:10:19 +0800 Subject: [PATCH] =?UTF-8?q?102.=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84?= =?UTF-8?q?=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86=E5=A2=9E=E5=8A=A0Go?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E5=88=87=E7=89=87=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 31 ++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 17832e44..33852898 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -265,7 +265,7 @@ func levelOrder(root *TreeNode) [][]int { ```go /** -102. 二叉树的层序遍历 +102. 二叉树的层序遍历 使用container包 */ func levelOrder(root *TreeNode) [][]int { res := [][]int{} @@ -296,6 +296,35 @@ func levelOrder(root *TreeNode) [][]int { 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. 二叉树的层序遍历:使用切片模拟队列,易理解 */