【发布时间】: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