遍历二叉树的先序中序后序相比较在输出语句的位置有改变。递归思想,将左子树和右子树进行递归调用,判断是否为空值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main

import "fmt"

type Student struct {<!-- -->//创建结构体
    name   string
    lnode  *Student
    rnode  *Student
}

func hshowall(head *Student) {<!-- -->//遍历二叉树,先序遍历二叉树,先将传进来的指针进行输出指针所指向的值,再将指针指向的的左子树和右子树进行递归
    if head != nil {<!-- -->
        fmt.Println(head.name)
        showall(head.lnode)
        showall(head.rnode)
    }
}
func mshowall(head *Student){<!-- -->//中序遍历二叉树,先将传进来的指针进行判断是否为空,如果不为空,则先将指针指向的左树进行递归
    if head !=nil{<!-- -->
        mshowall(head.lnode)
        fmt.Println(head.name)
        mshowall(head.rnode)
    }
}
func lshowall(head *Student){<!-- -->//后序遍历二叉树,先将左子树的指针传入,再进行递归
    if head !=nil{<!-- -->
        lshowall(head.lnode)
        lshowall(head.rnode)
        fmt.Println(head.name)
    }
}
func main() {<!-- -->
    student := Student{<!-- -->name: "xiang"}
    stu := Student{<!-- -->name: "left"}
    stu1 := Student{<!-- -->name: "right"}
    student.lnode = &stu
    student.rnode = &stu1
    hshowall(&student)
}