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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
package main
type TreeNode struct {
Left *TreeNode
Right *TreeNode
Val int
}
func main(){
root := &TreeNode{
Left: &TreeNode{
Left: &TreeNode{Val: 4},
Right: &TreeNode{Val: 5},
Val: 2,
},
Right: &TreeNode{
Val: 3,
Left: &TreeNode{Val: 6},
Right: &TreeNode{Val: 7, },
},
Val: 1,
}
preorder(root)
}
// 前序遍历
func preorder(root *TreeNode){
if root == nil {
return
}
fmt.Println("vav:", root.Val)
preorder(root.Left)
preorder(root.Right)
}
// 中序遍历
func inorder (root *TreeNode) {
if root == nil {
return
}
inorder(root.Left)
fmt.Println("inorder:", root.Val)
inorder((root.Right))
}
// 后序遍历
func postorder(root *TreeNode) {
if root == nil {
return
}
postorder(root.Left)
postorder(root.Right)
fmt.Println("postorder:", root.Val)
}
|