Skip to content

Instantly share code, notes, and snippets.

@chez-shanpu
Last active May 31, 2020 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chez-shanpu/056e0d6ae98c6e0c1e79c2b6200ab1a8 to your computer and use it in GitHub Desktop.
Save chez-shanpu/056e0d6ae98c6e0c1e79c2b6200ab1a8 to your computer and use it in GitHub Desktop.
二分探索木
package main
import "fmt"
type binaryTree struct {
root *node
}
type node struct {
value int
left *node
right *node
}
func (n *node) add(val int) {
if val < n.value {
if n.left != nil {
n.left.add(val)
} else {
n.left = &node{value: val}
}
} else {
if n.right != nil {
n.right.add(val)
} else {
n.right = &node{value: val}
}
}
}
func (b *binaryTree) add(val int) {
if b.root == nil {
b.root = &node{value: val}
} else {
b.root.add(val)
}
}
func (b *binaryTree) contains(t int) bool {
n := b.root
for {
if t == n.value {
return true
} else if t < n.value {
if n.left == nil {
return false
}
n = n.left
} else if t > n.value {
if n.right == nil {
return false
}
n = n.right
}
}
}
func main() {
b := binaryTree{}
b.add(5)
b.add(13)
b.add(3)
fmt.Println(b.contains(13))
fmt.Println(b.contains(4))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment