Created
February 15, 2014 18:59
-
-
Save defp/9023626 to your computer and use it in GitHub Desktop.
go run binary_tree.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type Tree struct { | |
Value int | |
Left, Right *Tree | |
} | |
func insert(t *Tree, v int) *Tree { | |
if t == nil { | |
return &Tree{v, nil, nil} | |
} | |
if v < t.Value { | |
t.Left = insert(t.Left, v) | |
return t | |
} | |
t.Right = insert(t.Right, v) | |
return t | |
} | |
func (tree *Tree) PreOrderWalk() { | |
if tree == nil { | |
return | |
} | |
fmt.Println("pre order walk:", tree.Value) | |
tree.Left.PreOrderWalk() | |
tree.Right.PreOrderWalk() | |
} | |
func (tree *Tree) InOrderWalk() { | |
if tree == nil { | |
return | |
} | |
tree.Left.InOrderWalk() | |
fmt.Println("In order walk:", tree.Value) | |
tree.Right.InOrderWalk() | |
} | |
func (tree *Tree) PostOrderWalk() { | |
if tree == nil { | |
return | |
} | |
tree.Left.PostOrderWalk() | |
tree.Right.PostOrderWalk() | |
fmt.Println("Post order walk:", tree.Value) | |
} | |
func main() { | |
datas := []int{4,2,1,3,5,6} | |
var tree *Tree | |
for _, v := range datas { | |
tree = insert(tree, v) | |
} | |
fmt.Println("PreOrderWalk:") | |
tree.PreOrderWalk() // should 4,2,1,3,5,6 | |
fmt.Println("InOrderWalk:") | |
tree.InOrderWalk() // should 1,2,3,4,5,6 | |
fmt.Println("PostOrderWalk:") | |
tree.PostOrderWalk() // should 1,3,2,6,5,4 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment