英文:
Trying to make a binary search tree, but I keep getting invalid memory address or nil pointer dereference errors
问题
我正在尝试创建一个二叉搜索树(BST),添加一个节点,并打印该节点中的数据,但是我一直收到无效的内存地址或空指针解引用错误。我知道我的指针有问题,我一直在调试它们,但是似乎无法弄对。请有人帮忙看一下,告诉我我犯了什么愚蠢的错误?
package main
import "fmt"
type node struct {
data int
left *node
right *node
}
type root struct {
root *node
}
func (bt *root) addNode(n *node, data int) {
if n == nil {
newNode := node{
data: data,
left: nil,
right: nil,
}
bt.root = &newNode
fmt.Println("Works")
} else if data < n.data {
bt.addNode(n.left, data)
} else {
bt.addNode(n.right, data)
}
}
func main() {
tree := root{root: nil}
tree.addNode(tree.root, 6)
fmt.Println(tree.root.data)
}
链接:https://go.dev/play/p/Cps4Y5mqYFM
英文:
I'm trying to create a BST, add a node, and print the data in that node, but I keep getting invalid memory address or nil pointer dereference errors. I know something is wrong with my pointers, and I've been fiddling around with them all afternoon, and I can't seem to get it right. Could someone please take a look and let me know what stupid mistake I'm making?
package main
import "fmt"
type node struct {
data int
left *node
right *node
}
type root struct {
root *node
}
func (bt root) addNode(n *node, data int) {
if n == nil {
newNode := node{
data: data,
left: nil,
right: nil,
}
n = &newNode
fmt.Println("Works")
} else if data < n.data {
bt.addNode(n.left, data)
} else {
bt.addNode(n.right, data)
}
}
func main() {
tree := root{root: nil}
tree.addNode(tree.root, 6)
fmt.Println(tree.root.data)
}
答案1
得分: 2
正如kostix正确指出的那样,为了使用该方法修改我的树,我必须传递一个指向原始树的指针的指针。谢谢,kostix!
package main
import "fmt"
type node struct {
data int
left *node
right *node
}
type root struct {
root *node
}
func (bt root) addNode(n **node, data int) {
if *n == nil {
newNode := node{
data: data,
left: nil,
right: nil,
}
*n = &newNode
fmt.Println("Works")
} else if data < (*n).data {
bt.addNode(&((*n).left), data)
} else {
bt.addNode(&((*n).right), data)
}
}
func main() {
tree := root{root: nil}
tree.addNode(&(tree.root), 6)
fmt.Println(tree.root.data)
}
英文:
As kostix correctly pointed out, in order to modify my tree with that method, I had to pass in a pointer to a pointer to the original tree. Thanks, kostix!
package main
import "fmt"
type node struct {
data int
left *node
right *node
}
type root struct {
root *node
}
func (bt root) addNode(n **node, data int) {
if *n == nil {
newNode := node{
data: data,
left: nil,
right: nil,
}
*n = &newNode
fmt.Println("Works")
} else if data < (*n).data {
bt.addNode(&((*n).left), data)
} else {
bt.addNode(&((*n).right), data)
}
}
func main() {
tree := root{root: nil}
tree.addNode(&(tree.root), 6)
fmt.Println(tree.root.data)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论