source
package main
// 트리 구조 정의
type Tree struct {
node *Node
}
// Node에 left와 right의 Node를 가지게 함
type Node struct{
value int
left *Node
right *Node
}
// 값 추가
// 트리 Node가 nil이면 현재 노드가 root 가 됨
// nil아 아니면 Node에 값을 추가
func (t *Tree) insert(value int) *Tree{
if t.node == nil{
t.node = &Node{ value : value}
} else {
t.node.insert(value)
}
return t
}
// 노드 값을 찾기
// nil 이면 false 반환
// nil이 아니고 값이 일치하면 true반환
// value의 값이 노트의 value 보다 작으면 왼쪽으로 탐색
// 크면 오른쪽으로 탐색
func ( n *Node) exists(value int) bool{
if n == nil {
return false
}
if n.value == value {
return true
}
if value <= n.value {
return n.left.exists( value)
} else {
return n.right.exists( value)
}
}
//출력
//왼쪽을 다 출력 하고, 없으면 본인, 그 다음 우측순으로
func printNode ( n *Node){
if n == nil {
return
}
printNode( n.left)
println( n.value)
printNode( n.right)
}
// 값 저장
// 저장할 값이 root보다 작으면 왼쪽으로 값 추가
// 크면 오른쪽으로 값을 추가
func ( n *Node) insert( value int){
if value <= n.value {
if n.left == nil {
n.left = &Node{ value : value}
} else {
n.left.insert( value)
}
} else {
if n.right == nil {
n.right = &Node{ value: value}
} else {
n.right.insert( value)
}
}
}
func main(){
t := &Tree{}
t.insert(6)
t.insert(3)
t.insert(8)
t.insert(10)
t.insert(1)
t.insert(2)
t.insert(7)
printNode( t.node)
println( t.node.exists(4))
println( t.node.exists(3))
}
output
1
2
3
6
7
8
10
false
true