如果两棵树具有相似的结构,并且它们之间的唯一区别是它们的子节点可以交换,也可以不交换,那么它们就可以称为同构树。例如:

     4                 4
   /   \             /   \
  2     6    and    6     2
 / \   / \         / \   / \
1   3 5   7       1   3 7   5

下面的代码应该是我在web中找到的正确实现,但由于某些原因,它不适用于上述树我做错什么了?
#include <iostream>
using namespace std;

class Node{

public:

    Node * left;
    Node * right;
    int val;

    Node(int v){
        left = NULL;
        right = NULL;
        val = v;
    }
};

bool isIsomorphic(Node* n1, Node *n2)
{
 // Both roots are NULL, trees isomorphic by definition
 if (n1 == NULL && n2 == NULL)
    return true;

 // Exactly one of the n1 and n2 is NULL, trees not isomorphic
 if (n1 == NULL || n2 == NULL)
    return false;

 if (n1->val != n2->val)
    return false;

 // There are two possible cases for n1 and n2 to be isomorphic
 // Case 1: The subtrees rooted at these nodes have NOT been "Flipped".
 // Both of these subtrees have to be isomorphic, hence the &&
 // Case 2: The subtrees rooted at these nodes have been "Flipped"
 return
 (isIsomorphic(n1->left,n2->left) && isIsomorphic(n1->right,n2->right))||
 (isIsomorphic(n1->left,n2->right) && isIsomorphic(n1->right,n2->left));
}

int main()
{
Node * na_4 = new Node(4);
Node * na_2 = new Node(2);
Node * na_6 = new Node(6);
Node * na_1 = new Node(1);
Node * na_3 = new Node(3);
Node * na_5 = new Node(5);
Node * na_7 = new Node(7);

na_4->left = na_2;
na_4->right = na_6;

na_2->left = na_1;
na_2->right = na_3;

na_6->left = na_5;
na_6->right = na_7;


Node * nb_4 = new Node(4);
Node * nb_6 = new Node(6);
Node * nb_2 = new Node(2);
Node * nb_1 = new Node(1);
Node * nb_3 = new Node(3);
Node * nb_7 = new Node(7);
Node * nb_5 = new Node(5);

nb_4->left = nb_6;
nb_4->right = nb_2;

nb_6->left = nb_1;
nb_6->right = nb_3;

nb_2->left = nb_7;
nb_2->right = nb_5;


if(isIsomorphic(na_4, nb_4)){
    cout << "Yes they are isomorphic" << endl;
}
else
{
    cout << "No there are not isomorphic" << endl;
}

return 0;
}

它输出它们不是同构的。

最佳答案

根据提供的定义,这些树不是同构的:
如果两棵树中的一棵可以通过一系列翻转(即交换多个节点的左、右子节点)从另一棵树中获得,则称之为同构树。任何级别的任意数量的节点都可以交换其子节点。两棵空树是同构的。
因为,在一棵树上,2有1和3个孩子,而在另一棵树上,2有7和5个孩子。
通过交换两个子节点,实际上是交换了它们的整个子树,而不仅仅是那些节点,让所有其他节点都留在原来的位置。
例如,这两个是同构的:

     4
   /   \
  2     6
 / \   / \
1   3 5   7

     4
   /   \
  6     2
 / \   / \
7   5 1   3

关于c++ - 查找两棵树是否同构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21475584/

10-10 04:47