Last active
May 31, 2020 15:25
-
-
Save chez-shanpu/056e0d6ae98c6e0c1e79c2b6200ab1a8 to your computer and use it in GitHub Desktop.
二分探索木
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 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