这篇文章主要讲解了“Go语言怎么实现二叉树遍历”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Go语言怎么实现二叉树遍历”吧!
1. 二叉树的定义
二叉树需满足的条件
① 本身是有序树
② 树中包含的各个节点的长度不能超过2,即只能是0、1或者2
2. 前序遍历
前序遍历二叉树的顺序:根——》左——》右
package mainimport "fmt"//定义结构体type Student struct {Name stringAge intScore float32left *Student //左子树指针right *Student //右子树指针}//二叉树定义func main() {//根节点var root Studentroot.Name = "root"root.Age = 18root.Score = 88//一级左子树var left1 Studentleft1.Name = "left1"left1.Age = 20left1.Score = 80root.left = &left1//一级右子树var right1 Studentright1.Name = "right1"right1.Age = 22right1.Score = 100root.right = &right1//二级左子树var left2 Studentleft2.Name = "left2"left2.Age = 25left2.Score = 90left1.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>}
3. 中序遍历
中序遍历:左——》根——》右
package mainimport "fmt"//定义结构体type Student struct {Name stringAge intScore float32left *Student //左子树指针right *Student //右子树指针}//二叉树定义func main() {//根节点var root Studentroot.Name = "root"root.Age = 18root.Score = 88//一级左子树var left1 Studentleft1.Name = "left1"left1.Age = 20left1.Score = 80root.left = &left1//一级右子树var right1 Studentright1.Name = "right1"right1.Age = 22right1.Score = 100root.right = &right1//二级左子树var left2 Studentleft2.Name = "left2"left2.Age = 25left2.Score = 90left1.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>}
4. 后序遍历
后序遍历:左——》右——》根
package mainimport "fmt"//定义结构体type Student struct {Name stringAge intScore float32left *Student //左子树指针right *Student //右子树指针}//二叉树定义func main() {//根节点var root Studentroot.Name = "root"root.Age = 18root.Score = 88//一级左子树var left1 Studentleft1.Name = "left1"left1.Age = 20left1.Score = 80root.left = &left1//一级右子树var right1 Studentright1.Name = "right1"right1.Age = 22right1.Score = 100root.right = &right1//二级左子树var left2 Studentleft2.Name = "left2"left2.Age = 25left2.Score = 90left1.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语言怎么实现二叉树遍历这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!