이 문제에서는 두 개의 나무가 제공됩니다. 우리의 임무는 두 트리가 동일한지 여부를 확인하는 코드를 작성하는 것입니다.
배열의 요소가 동일한 값과 방향을 가지면 두 트리가 동일하다고 합니다.
예
<강한>

두 트리 모두 동일한 값과 요소의 위치를 가지므로 두 트리가 동일합니다.
두 트리가 동일한지 확인하기 위해 노드 노드에서 각 노드로 이동하여 단계적으로 동등성을 확인하고 노드가 같지 않은 지점에서 -1을 반환하면 트리가 동일하지 않음을 나타내며 전체 트리가 탐색되거나 두 트리가 모두 비어 있는 경우 1을 반환하여 트리가 동일함을 나타냅니다.
위 솔루션의 작동을 설명하는 프로그램,
예시
#include <iostream>
using namespace std;
class node{
public:
int data;
node* left;
node* right;
};
node* insertNode(int data){
node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return(Node);
}
int isIdentricalTrees(node* tree1, node* tree2){
if (tree1 == NULL && tree2 == NULL)
return 1;
if (tree1 != NULL && tree2 != NULL){
return( tree1->data == tree2->data && isIdentricalTrees(tree1->left,
tree2->left) && isIdentricalTrees(tree1->right, tree2->right) );
}
return 0;
}
int main(){
node *root1 = insertNode(4);
node *root2 = insertNode(4);
root1->left = insertNode(5);
root1->right = insertNode(0);
root1->left->left = insertNode(1);
root1->left->right = insertNode(9);
root1->right->left = insertNode(7);
root2->left = insertNode(5);
root2->right = insertNode(0);
root2->left->left = insertNode(1);
root2->left->right = insertNode(9);
root2->right->left = insertNode(7);
cout<<"Both the given trees are ";
if(isIdentricalTrees(root1, root2))
cout<<"identical";
else
cout<<"identical";
return 0;
} 출력
Both the given trees are identical