doumi7861 2018-05-07 04:30
浏览 35
已采纳

为什么在“遍历:等效二叉树”中将遍历从“有序”更改为“前/后”才能使答案错误?

In the concurrency section of Golang tour there is an exercise as follows. The problem statement wants to verify that two input trees are as the same or not.

The problem here is when we changing the traversal order from in-order to pre/post-order it fails. i.e the bellow code works correctly

if t != nil {
    traverse(t.Left, ch)
    ch <- t.Value
    traverse(t.Right, ch)
}

but if we first put the value to channel and then went to node's children its answer became wrong(run this and this for same input which output is difference).

Since we used the same code for traversing its expected that the order should not matter(i.e values goes to the channel in the same order...).

PS: You can find more answers to this exercise here.

  • 写回答

1条回答 默认 最新

  • duanpacan9388 2018-05-07 06:26
    关注

    The answer for this one is rather related to data structures rather than Golang syntax and has to do with Binary Search Tree properties.

    As the documentation states tree.New func returns a random constructed key:

    New returns a new, random binary tree holding the values k, 2k, ..., 10k.

    An inorder traversal promises the output to be sorted, but it isn't the case for preorder and postorder traversal and therefore the output would not be equal for these traversals.

    Consider the following tree:

           4
          / \
         2   5
        / \
       1   3
    

    InOrder traverse: 1, 2, 3, 4, 5

    PostOrder traverse: 1 3 2 5 4

    For more information: Binary Trees

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)