你能帮忙搜索功能吗,它总是返回零,我不明白为什么
func BTreeSearchItem(root *TreeNode, elem string) *TreeNode {
if root == nil {
return nil
}
if root.Data < elem {
return BTreeSearchItem(root.Left, elem)
} else if root.Data > elem {
return BTreeSearchItem(root.Right, elem)
}
return root
}
试图这样做,但它返回 4 而不是 7
func BTreeSearchItem(root *TreeNode, elem string) *TreeNode {
if root == nil {
return nil
}
if root.Data < elem {
BTreeSearchItem(root.Left, elem)
} else if root.Data > elem {
BTreeSearchItem(root.Right, elem)
}
return root
}
完整代码是
package main
import "fmt"
type TreeNode struct {
Left, Right, Parent *TreeNode
Data string
}
func BTreeSearchItem(root *TreeNode, elem string) *TreeNode {
if root == nil {
return nil
}
if root.Data < elem {
BTreeSearchItem(root.Left, elem)
} else if root.Data > elem {
BTreeSearchItem(root.Right, elem)
}
return root
}
func BTreeInsertData(root *TreeNode, data string) *TreeNode {
if root == nil {
return &TreeNode{Data: data}
}
if root.Data == data {
return nil
}
if root.Data > data {
if root.Left == nil {
root.Left = &TreeNode{Data: data}
}
return BTreeInsertData(root.Left, data)
}
if root.Data < data {
if root.Right == nil {
root.Right = &TreeNode{Data: data}
}
return BTreeInsertData(root.Right, data)
}
return root
}
func main() {
root := &TreeNode{Data: "4"}
BTreeInsertData(root, "1")
BTreeInsertData(root, "7")
BTreeInsertData(root, "5")
selected := BTreeSearchItem(root, "7")
fmt.Print("Item selected -> ")
if selected != nil {
fmt.Println(selected.Data)
} else {
fmt.Println("nil")
}
fmt.Print("Parent of selected item -> ")
if selected.Parent != nil {
fmt.Println(selected.Parent.Data)
} else {
fmt.Println("nil")
}
}
搜索了互联网并通过方法找到了很多,但我需要作为功能。我是编程的初学者,所以我很难理解
PlayGoundLink
白衣非少年
一只甜甜圈
相关分类