欢迎大家来到IT世界,在知识的湖畔探索吧!
输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]
欢迎大家来到IT世界,在知识的湖畔探索吧!
欢迎大家来到IT世界,在知识的湖畔探索吧!输入:root = [1] 输出:[[1]]
以下是我的代码实现
package main import ( "fmt" "testing" ) // TreeNode represents a node in a binary tree type ( TreeDocument struct { Val int Left *TreeDocument Right *TreeDocument } ) func loopLayerArr(root *TreeDocument) [][]int { queues := []*TreeDocument{root} result := make([][]int, 0) for len(queues) > 0 { queueSize := len(queues) layerArr := make([]int, queueSize) for i := 0; i < queueSize; i++ { queue := queues[0] layerArr[i] = queue.Val if queue.Left != nil { queues = append(queues, queue.Left) } if queue.Right != nil { queues = append(queues, queue.Right) } queues = queues[1:] } result = append(result, layerArr) } return result } func TestLayerLoop(t *testing.T) { // 构建一个示例二叉树 root := &TreeDocument{ Val: 3, Left: &TreeDocument{ Val: 9, Left: &TreeDocument{ Val: 7, }, Right: &TreeDocument{ Val: 8, }, }, Right: &TreeDocument{ Val: 20, Left: &TreeDocument{ Val: 15, }, Right: &TreeDocument{ Val: 7, }, }, } result := loopLayerArr(root) fmt.Println("result => ", result) }
代码比较简单,仅供参考和自己后续的回顾
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/95559.html