【问题标题】:How to find whether two trees are structurally same using level order traversal?如何使用级别顺序遍历查找两棵树在结构上是否相同?
【发布时间】:2014-06-06 15:56:44
【问题描述】:

我想出了一个算法来检查两棵树在结构上是否相似,即两棵树中相应节点的数据可能不同,但如果 tree1 中的节点有一个左孩子,那么它在 tree2 中的对应节点必须有一个左孩子也是。

算法(节点 * root1,节点 * root2):

    1. Create 2 queues Q1,Q2 and enqueue root1 and root2.
    2. while(Q1 and Q2 are not empty)
         2.a temp1 = deQ(Q1);
         2.b temp2 = deQ(Q2);
           2.c if temp1 has left child then enqueue temp1's left child in Q1
           2.d if temp2 has left child then enqueue temp2's left child in Q2
           2.e if temp1 has right child then enqueue temp1's right child in Q1
           2.f if temp2 has right child then enqueue temp2's right child in Q2
         2.g now check if the size of Q1 and Q2 is equal
         2.h if the size is equal then continue else the two trees are not similar
    3.  End

这个算法正确吗?

【问题讨论】:

  • 不,不是。它将识别只有左孩子的节点与只有右孩子的节点相同。
  • @NicoSchertler 啊!这是一个有效的观点!你能指出一个更正吗?
  • 那么,您显然是指二叉树树,对吗?问题的陈述从未提到,虽然算法似乎依赖于此。难道真的是你应该使用通用树,而不仅仅是二元树吗? (当然,任何树都可以映射到等效的二叉树,但仍然......)

标签: algorithm tree binary-tree pseudocode tree-traversal


【解决方案1】:

目前,您的算法无法正常工作。例如,如果tree1 root 只有一个右孩子,tree2 只有一个左孩子,那么您的算法将输出误报。

您必须按如下方式修改算法。这是一种递归方法,但还有其他可能的方法。

Algorithm(node * root1, node * root2) :

   // if exactly one is NULL and other is not, return false.
   if ( root1 && !root2 ) || ( !root1 && root2 )
       return 0.

   // if both are NULL, return true.
   if ( !root1 && !root2 )
       return 1.

   // Both are valid nodes. So now check there respective child sub-trees.
   return Algorithm( root1->left, root2->left ) && Algorithm( root1->right, root2->right )

你的算法:

    Algorithm(node * root1, node * root2) :
        1. Create 2 queues Q1,Q2 and enqueue root1 and root2.
        // here you skip the Null check for root1 and root2. Should be added.
        2. while(Q1 is not empty or Q2 is not empty)
             2.a temp1 = deQ(Q1);
             2.b temp2 = deQ(Q2);
   // Now Compare the respective children of temp1 & temp2. If not equal, then return false.
               2.c if temp1 has left child then enqueue temp1's left child in Q1
               2.d if temp2 has left child then enqueue temp2's left child in Q2
               2.e if temp1 has right child then enqueue temp1's right child in Q1
               2.f if temp2 has right child then enqueue temp2's right child in Q2
        3.  return true.

【讨论】:

  • 感谢阿布舍克的回答!但我正在寻找一种非递归方法。你能尝试纠正这个算法吗?
  • @Dubby 在你的算法中添加了修改
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 1970-01-01
相关资源
最近更新 更多