Go 学习之结构体二叉树 (二)

一、二叉树定义

type Student struct {
       Name string
       left* Student
       right* Student
}

如果每个节点有两个指针分别用来指向左子树和右子树,我们把这样的结构叫做二叉树。

代码练习

file

前序遍历

package main

import "fmt"

type Student struct {
    Name string
    Age int
    Score float32
    left *Student
    right *Student
}

func trans(root *Student) {
    if root == nil {
        return
    }

    fmt.Println(root)
    trans(root.left)
    trans(root.right)

}

func main()  {
    var root *Student = new(Student)

    root.Name = "Lily"
    root.Age = 18
    root.Score = 80

    var left1 *Student = new(Student)
    left1.Name = "LauChao"
    left1.Age = 50
    left1.Score = 90

    root.left = left1

    var right1 *Student = new(Student)
    right1.Name = "Andy"
    right1.Age = 50
    right1.Score = 90

    root.right = right1

    var left2 *Student = new(Student)
    left2.Name = "Xiu"
    left2.Age = 50
    left2.Score = 90

    left1.left = left2

    trans(root)

}

结果打印:

&{Lily 18 80 0xc420014150 0xc420014180}
&{LauChao 50 90 0xc4200141b0 <nil>}
&{Xiu 50 90 <nil> <nil>}
&{Andy 50 90 <nil> <nil>}

为者常成,行者常至