ในปัญหานี้ เราได้รับต้นไม้สองต้น งานของเราคือเขียนโค้ดเพื่อตรวจสอบว่าต้นไม้ทั้งสองต้นเหมือนกันหรือไม่
กล่าวกันว่าต้นไม้สองต้นจะเหมือนกันหากองค์ประกอบของอาร์เรย์มีค่าและการวางแนวเหมือนกัน
ตัวอย่าง

เนื่องจากต้นไม้ทั้งสองมีค่าและตำแหน่งขององค์ประกอบเหมือนกัน ต้นไม้ทั้งสองจึงเหมือนกัน
ในการตรวจสอบว่าต้นไม้สองต้นเหมือนกันหรือไม่ เราจะไปจากโหนดโหนดไปยังแต่ละโหนดของ และตรวจสอบความเท่าเทียมกันทีละขั้นตอน และหากจุดใดไปยังโหนดไม่เท่ากับผลตอบแทน -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