你能帮忙搜索功能吗,它总是返回零,我不明白为什么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 而不是 7func 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 mainimport "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
2 回答
白衣非少年
TA贡献1155条经验 获得超0个赞
好的,https://play.golang.org/p/gQmdYLfAvIY此代码有效,BTreeInsertData
忘记添加Parant
并且BTreeSearchItem
我不匹配Right
并且Left
- 2 回答
- 0 关注
- 150 浏览
添加回答
举报
0/150
提交
取消