78 lines
1.3 KiB
Go
78 lines
1.3 KiB
Go
package main
|
|
|
|
import "fmt"
|
|
|
|
type TreeNode struct {
|
|
Val int
|
|
Left *TreeNode
|
|
Right *TreeNode
|
|
}
|
|
|
|
func inorder(root *TreeNode) {
|
|
if root == nil {
|
|
return
|
|
}
|
|
inorder(root.Left)
|
|
fmt.Print(root.Val)
|
|
inorder(root.Right)
|
|
}
|
|
|
|
func preorder(root *TreeNode) {
|
|
if root == nil {
|
|
return
|
|
}
|
|
fmt.Print(root.Val)
|
|
preorder(root.Left)
|
|
preorder(root.Right)
|
|
}
|
|
|
|
func postorder(root *TreeNode) {
|
|
if root == nil {
|
|
return
|
|
}
|
|
postorder(root.Left)
|
|
postorder(root.Right)
|
|
fmt.Print(root.Val)
|
|
}
|
|
|
|
func reverserOrder(root *TreeNode) {
|
|
if root == nil {
|
|
return
|
|
}
|
|
reverserOrder(root.Right)
|
|
fmt.Print(root.Val)
|
|
reverserOrder(root.Left)
|
|
}
|
|
|
|
func traverse(root *TreeNode, res *[]int){
|
|
if root == nil {
|
|
return
|
|
}
|
|
traverse(root.Left, res)
|
|
*res = append(*res, root.Val)
|
|
traverse(root.Right, res)
|
|
}
|
|
func inorderTraversal(root *TreeNode) []int {
|
|
var result []int
|
|
traverse(root, &result)
|
|
return result
|
|
}
|
|
|
|
func main() {
|
|
n10 := TreeNode{Val: 2}
|
|
n9 := TreeNode{Val: 5}
|
|
n8 := TreeNode{Val: 7}
|
|
n7 := TreeNode{Val: 6, Left: &n9, Right: &n8}
|
|
n6 := TreeNode{Val: 3, Left: &n10}
|
|
n5 := TreeNode{Val: 4, Left: &n6, Right: &n7}
|
|
|
|
// inorder(&n5)
|
|
// fmt.Println()
|
|
// preorder(&n5)
|
|
// fmt.Println()
|
|
// postorder(&n5)
|
|
// fmt.Println()
|
|
// reverserOrder(&n5)
|
|
res := inorderTraversal(&n5)
|
|
fmt.Print(res)
|
|
}
|