我有两个我期望表现相同的函数,但是给出了不同的结果。试图了解为什么
当我遇到问题时,我正在写二进制搜索树遍历,然后稍微改变语法更改修复了它,但我不明白为什么它在第一个palce中不起作用。我提供的两个代码示例我希望以完全相同的方式运行,但事实并非如此。
一个将Curr变量设置为左节点Curr.Left,然后递归地调用InorderRecursive,而另一个则在Curr.Left本身上直接调用InorderRecursive。
type BST struct {
value int
left *BST
right *BST
}
不起作用(这确实返回错误的值):
func (tree *BST) InOrderRecursive(values []int) []int {
curr := tree
if curr.left != nil {
curr = curr.left
values = curr.InOrderRecursive(values)
}
values = append(values, curr.value)
if curr.right != nil {
curr = curr.right
values = curr.InOrderRecursive(values)
}
return values
}
工作(返回正确的值):
func (tree *BST) InOrderRecursive(values []int) []int {
curr := tree
if curr.left != nil {
values = curr.left.InOrderRecursive(values)
}
values = append(values, curr.value)
if curr.right != nil {
values = curr.right.InOrderRecursive(values)
}
return values
}
有人可以解释这两个代码示例中的区别以及不同行为的原因吗?
I was writing a binary search tree traversal when I came across a problem, and then a slight syntax change fixed it but I don't understand why it wasn't working in the first palce. The two code examples I provide I would expect to run the exact same way but they don't.
One sets the curr variable to it's left node curr.left, then recursively calls the InOrderRecursive, while the other calls InOrderRecursive directly on curr.left itself.
type BST struct {
value int
left *BST
right *BST
}
Does not work (This does return but with the wrong values):
func (tree *BST) InOrderRecursive(values []int) []int {
curr := tree
if curr.left != nil {
curr = curr.left
values = curr.InOrderRecursive(values)
}
values = append(values, curr.value)
if curr.right != nil {
curr = curr.right
values = curr.InOrderRecursive(values)
}
return values
}
Works (returns the correct values):
func (tree *BST) InOrderRecursive(values []int) []int {
curr := tree
if curr.left != nil {
values = curr.left.InOrderRecursive(values)
}
values = append(values, curr.value)
if curr.right != nil {
values = curr.right.InOrderRecursive(values)
}
return values
}
Could someone please explain the difference in these two code examples and the reason for the different behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个版本有一个小错误。如果
curr.left
在版本1中不是零,则values = append(values,curr.value)
会将左子节点的值附加到列表中,而不是当前节点,因为curr
现在等于curr.left
在if范围之外。更具体地说,The first version has a slight bug. If
curr.left
is not nil in version 1, thenvalues = append(values, curr.value)
will append the left child node's value to the list, not the current node, sincecurr
is now equal tocurr.left
outside of the if scope. More specifically,