用golang写一个二叉搜索树
时间: 2023-07-24 19:28:24 浏览: 29
下面是用 Golang 实现的二叉搜索树代码,包括节点结构体和基本的插入和查找操作:
```go
package main
import (
"fmt"
)
// 节点结构体
type Node struct {
Key int // 关键字
Left *Node // 左子节点
Right *Node // 右子节点
}
// 插入节点
func (n *Node) Insert(key int) {
if n.Key < key {
if n.Right == nil {
n.Right = &Node{Key: key}
} else {
n.Right.Insert(key)
}
} else if n.Key > key {
if n.Left == nil {
n.Left = &Node{Key: key}
} else {
n.Left.Insert(key)
}
}
}
// 查找节点
func (n *Node) Search(key int) bool {
if n == nil {
return false
}
if n.Key < key {
return n.Right.Search(key)
} else if n.Key > key {
return n.Left.Search(key)
}
return true
}
func main() {
root := &Node{Key: 5} // 根节点
root.Insert(3)
root.Insert(8)
root.Insert(2)
root.Insert(4)
root.Insert(7)
root.Insert(9)
fmt.Println(root.Search(5)) // true
fmt.Println(root.Search(2)) // true
fmt.Println(root.Search(6)) // false
fmt.Println(root.Search(10)) // false
}
```
在这个代码中,我们使用 `Node` 结构体来表示二叉搜索树的节点,包括 `Key` 关键字、`Left` 左子节点和 `Right` 右子节点。在 `Insert` 方法中,我们根据关键字的大小来决定插入到左子树还是右子树,并递归地调用子节点的 `Insert` 方法。在 `Search` 方法中,我们通过递归查找子树来寻找目标节点。最后,在主函数中,我们创建了一个根节点,插入了几个节点,并查找了一些关键字。
相关推荐
















