二叉树:golang实现层序遍历

二叉树:golang实现层序遍历一大早起来练习基础算法 今天练习下二叉树的层序遍历 对应 leetcode 第 102 题给你二叉树的根节点 root 返回其节点值的 层序遍历 即逐层地 从左到右访问所有节点

欢迎大家来到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

(0)
上一篇 9小时前
下一篇 8小时前

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们YX

mu99908888

在线咨询: 微信交谈

邮件:itzsgw@126.com

工作时间:时刻准备着!

关注微信