这篇文章主要讲解了“Go语言怎么实现二叉树遍历”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Go语言怎么实现二叉树遍历”吧!
二叉树需满足的条件
① 本身是有序树
② 树中包含的各个节点的长度不能超过2,即只能是0、1或者2
前序遍历二叉树的顺序:根——》左——》右
package main import "fmt" //定义结构体 type Student struct { Name string Age int Score float32 left *Student //左子树指针 right *Student //右子树指针 } //二叉树定义 func main() { //根节点 var root Student root.Name = "root" root.Age = 18 root.Score = 88 //一级左子树 var left1 Student left1.Name = "left1" left1.Age = 20 left1.Score = 80 root.left = &left1 //一级右子树 var right1 Student right1.Name = "right1" right1.Age = 22 right1.Score = 100 root.right = &right1 //二级左子树 var left2 Student left2.Name = "left2" left2.Age = 25 left2.Score = 90 left1.left = &left2 //调用遍历函数 Req(&root) } //递归算法遍历整个二叉树 func Req(tmp *Student) { for tmp == nil { return } fmt.Println(tmp) //遍历左子树 Req(tmp.left) //遍历右子树 Req(tmp.right) }
输出结果如下
&{root 18 88 0xc0000c0480 0xc0000c04b0}
&{left1 20 80 0xc0000c04e0 <nil>}
&{left2 25 90 <nil> <nil>}
&{right1 22 100 <nil> <nil>}
中序遍历:左——》根——》右
package main import "fmt" //定义结构体 type Student struct { Name string Age int Score float32 left *Student //左子树指针 right *Student //右子树指针 } //二叉树定义 func main() { //根节点 var root Student root.Name = "root" root.Age = 18 root.Score = 88 //一级左子树 var left1 Student left1.Name = "left1" left1.Age = 20 left1.Score = 80 root.left = &left1 //一级右子树 var right1 Student right1.Name = "right1" right1.Age = 22 right1.Score = 100 root.right = &right1 //二级左子树 var left2 Student left2.Name = "left2" left2.Age = 25 left2.Score = 90 left1.left = &left2 //调用遍历函数 Req(&root) } //递归算法遍历整个二叉树 func Req(tmp *Student) { for tmp == nil { return } //遍历左子树 Req(tmp.left) //输出root节点 fmt.Println(tmp) //遍历右子树 Req(tmp.right) }
输出结果如下
&{left2 25 90 <nil> <nil>}
&{left1 20 80 0xc000114510 <nil>}
&{root 18 88 0xc0001144b0 0xc0001144e0}
&{right1 22 100 <nil> <nil>}
后序遍历:左——》右——》根
package main import "fmt" //定义结构体 type Student struct { Name string Age int Score float32 left *Student //左子树指针 right *Student //右子树指针 } //二叉树定义 func main() { //根节点 var root Student root.Name = "root" root.Age = 18 root.Score = 88 //一级左子树 var left1 Student left1.Name = "left1" left1.Age = 20 left1.Score = 80 root.left = &left1 //一级右子树 var right1 Student right1.Name = "right1" right1.Age = 22 right1.Score = 100 root.right = &right1 //二级左子树 var left2 Student left2.Name = "left2" left2.Age = 25 left2.Score = 90 left1.left = &left2 //调用遍历函数 Req(&root) } //递归算法遍历整个二叉树 func Req(tmp *Student) { for tmp == nil { return } //遍历左子树 Req(tmp.left) //遍历右子树 Req(tmp.right) //输出root节点 fmt.Println(tmp) }
输出结果如下
&{left2 25 90 <nil> <nil>}
&{left1 20 80 0xc0000c04e0 <nil>}
&{right1 22 100 <nil> <nil>}
&{root 18 88 0xc0000c0480 0xc0000c04b0}
感谢各位的阅读,以上就是“Go语言怎么实现二叉树遍历”的内容了,经过本文的学习后,相信大家对Go语言怎么实现二叉树遍历这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。