先序遍历二叉树失败

huangapple go评论82阅读模式
英文:

preorder binary tree traversal fails

问题

我在go tour中遇到了等价二叉树的问题。

我编写了一个Walker()函数来按照节点-左子树-右子树的顺序遍历树,然后使用Same()函数来测试两个相同的二叉树是否等价。

这是我的代码链接:https://go.dev/play/p/vakNgx_CD3L

请查看链接中的go代码中的注释。由于某种原因,使用这种遍历顺序时,等价性测试失败了,但是将顺序切换为左子树-节点-右子树或右子树-节点-左子树时可以正常工作。

打印输出也让我感到困惑。当运行时,为什么从遍历树1得到的前10个数字与从遍历树2得到的第二组10个数字不匹配呢?

10
5
3
1
2
4
7
6
9
8
7
4
2
1
3
5
6
9
8
10
false
false
英文:

I am having trouble with the equivalent binary trees exercise on the go tour.

I've written a Walker() function to traverse the tree in node-left-right order, then used the Same() function to test two identical binary trees for equivalence.

Here is a link to my code: https://go.dev/play/p/vakNgx_CD3L

See comments in the linked go code. For some reason, with this traversal order, the equivalence tests fails when it should work. Switching the order to left-node-right or right-node-left works, though.

The print output also confuses me. This is the result when run. Why don't the first 10 numbers from traversing tree 1 match the second set of 10 numbers from traversing tree 2?

10
5
3
1
2
4
7
6
9
8
7
4
2
1
3
5
6
9
8
10
false
false

答案1

得分: 2

我认为问题在于你使用了https://pkg.go.dev/golang.org/x/tour/tree#New函数,该函数返回一个包含1,000到10,000个值的随机二叉树。

这里的关键是"Random"这个词,所以你不能期望从调用tree.New(1)函数得到相同的二叉树作为输出。

尽管树节点的值将从1到10(当k=1时)不等,但返回的树的顺序将是不同的。如果你使用.String()函数打印树,你可以清楚地看到这一点。

请查看下面的playground代码,我在其中打印了树,清楚地显示了每次调用tree.New函数返回的树都是不同的。
https://go.dev/play/p/WkF8frfno17

希望这可以帮到你:)。

英文:

I think the problem here is, you are using the https://pkg.go.dev/golang.org/x/tour/tree#New function which returns a random binary tree from 1k to 10k values.

The "Random" word is of importance here, so you can not expect to get same binary tree as a output from a call to tree.New(1) function.

Though the tree nodes will have values from 1 to 10 (incase of k=1) the order of the tree returned will be diffrent. You can see this clearly if you print the tree with the .String() function.
Take a look at below playground code where I have printed the tree which clearly shows the returned tree will be different at each call to the tree.New function.
https://go.dev/play/p/WkF8frfno17

I hope this helps :).

huangapple
  • 本文由 发表于 2022年7月5日 12:28:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/72864024.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定