目录
1.结构定义
type Node struct {
data int
parent *Node
left *Node
right *Node
}
type BinaryTree struct {
root *Node
}
2.InsertItem()
func (tree *BinaryTree) InsertItem(i int) {
if tree.root == nil {
tree.root = &Node{data: i}
return
}
currentnode := tree.root
for {
if i > currentnode.data {
if currentnode.right == nil {
currentnode.right = &Node{data: i, parent: currentnode}
return
}
currentnode = currentnode.right
} else {
if currentnode.left == nil {
currentnode.left = &Node{data: i, parent: currentnode}
return
}
currentnode = currentnode.left
}
}
}
3.SearchItem()
func (tree *BinaryTree) SearchItem(i int) (*Node, bool) {
if tree.root == nil {
return nil, false
}
current := tree.root
for current != nil {
if i == current.data {
return current, true
} else if i > current.data {
current = current.right
} else if i < current.data {
current = current.left
}
}
return nil, false
}
4.PreorderTraversal()
func (tree *BinaryTree) PreorderTraversal(subtree *Node, callback func(i int)) {
callback(subtree.data)
if subtree.left != nil {
tree.PreorderTraversal(subtree.left, callback)
}
if subtree.right != nil {
tree.PreorderTraversal(subtree.right, callback)
}
}
5.InorderTraversal()
func (tree *BinaryTree) InorderTraversal(subtree *Node, callback func(i int)) {
if subtree.left != nil {
tree.PreorderTraversal(subtree.left, callback)
}
callback(subtree.data)
if subtree.right != nil {
tree.PreorderTraversal(subtree.right, callback)
}
}
6.PostorderTraversal()
func (tree *BinaryTree) PostorderTraversal(subtree *Node, callback func(i int)) {
if subtree.left != nil {
tree.PreorderTraversal(subtree.left, callback)
}
if subtree.right != nil {
tree.PreorderTraversal(subtree.right, callback)
}
callback(subtree.data)
}