From 8364dcd0f181e6152f00b6f6bf415f296b451e0b Mon Sep 17 00:00:00 2001 From: jwcen Date: Wed, 7 Dec 2022 19:43:34 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9A=84=E5=B1=82?= =?UTF-8?q?=E5=BA=8F=E9=81=8D=E5=8E=86=EF=BC=9A=E4=BD=BF=E7=94=A8=E5=88=87?= =?UTF-8?q?=E7=89=87=E6=A8=A1=E6=8B=9F=E9=98=9F=E5=88=97=EF=BC=8C=E6=98=93?= =?UTF-8?q?=E7=90=86=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 30 +++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index 9985971f..bc78cb36 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -271,6 +271,36 @@ func levelOrder(root *TreeNode) [][]int { return res } + +/** +102. 二叉树的层序遍历:使用切片模拟队列,易理解 + */ +func levelOrder(root *TreeNode) (res [][]int) { + if root == nil { + return + } + + curLevel := []*TreeNode{root} // 存放当前层节点 + for len(curLevel) > 0 { + nextLevel := []*TreeNode{} // 准备通过当前层生成下一层 + vals := []int{} + + for _, node := range curLevel { + vals = append(vals, node.Val) // 收集当前层的值 + // 收集下一层的节点 + if node.Left != nil { + nextLevel = append(nextLevel, node.Left) + } + if node.Right != nil { + nextLevel = append(nextLevel, node.Right) + } + } + res = append(res, vals) + curLevel = nextLevel // 将下一层变成当前层 + } + + return +} ``` javascript代码: