C++ program to check if two trees are identical using recursion
Description:
This Program is to check if two trees are identical using recursion.
For Example:
Input :
The Elements of tree1 : 1 , 2, 3, 4, 5
The Elements of tree2 : 1 , 2, 3, 4, 5
Output :
Both tree are identical.
Program :
//C++ program to check if two trees are identical using recursion
#include<bits/stdc++.h> usingnamespacestd;
// tree node structNode { int data; Node *left, *right; };
// returns a new tree Node Node* newNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } //return true if they are identical boolTrees(struct Node* root1, struct Node* root2) { // if both empty if (root1==NULL && root2==NULL) returntrue;
// if both are non empty then comparing them if (root1!=NULL && root2!=NULL) { return ( root1->data == root2->data && Trees(root1->left, root2->left) && Trees(root1->right, root2->right) ); }
Comments