« Check if two trees are structurally identical
Structurally identical
Given two generic trees, return true if they are structurally identical. Otherwise return false.
Structural Identical:
If the two given trees are made of nodes with the same values and the nodes are arranged in the same way, then the trees are called identical.
Input format :
The first line of input contains data of the nodes of the first tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space.
The following line of input contains data of the nodes of the second tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space.
Output format :
The first and only line of output contains true, if the given trees are structurally identical and false, otherwise.
Constraints:
Time Limit: 1 sec
Sample Input 1 :
10 3 20 30 40 2 40 50 0 0 0 0
10 3 20 30 40 2 40 50 0 0 0 0
Sample Output 1 :
true
Sample Input 2 :
10 3 20 30 40 2 40 50 0 0 0 0
10 3 2 30 40 2 40 50 0 0 0 0
Sample Output 2:
false
1#include <iostream>2#include <queue>3#include <vector>4using namespace std;56template <typename T>7class TreeNode {8 public:9 T data;10 vector<TreeNode<T>*> children;1112 TreeNode(T data) { this->data = data; }1314 ~TreeNode() {15 for (int i = 0; i < children.size(); i++) {16 delete children[i];17 }18 }19};2021bool areIdentical(TreeNode<int> *root1, TreeNode<int> * root2) {22 // Write your code here23 if((root1->data != root2->data) ||( root1->children.size() != root2->children.size())){24 return false;25 }26 for(int i=0; i<root1->children.size(); i++){27 bool ans = areIdentical(root1->children[i], root2->children[i]);28 if(ans == false){29 return false;30 }31 }32 return true;33}3435TreeNode<int>* takeInputLevelWise() {36 int rootData;37 cin >> rootData;38 TreeNode<int>* root = new TreeNode<int>(rootData);3940 queue<TreeNode<int>*> pendingNodes;4142 pendingNodes.push(root);43 while (pendingNodes.size() != 0) {44 TreeNode<int>* front = pendingNodes.front();45 pendingNodes.pop();46 int numChild;47 cin >> numChild;48 for (int i = 0; i < numChild; i++) {49 int childData;50 cin >> childData;51 TreeNode<int>* child = new TreeNode<int>(childData);52 front->children.push_back(child);53 pendingNodes.push(child);54 }55 }5657 return root;58}5960int main() {61 TreeNode<int>* root1 = takeInputLevelWise();62 TreeNode<int>* root2 = takeInputLevelWise();63 cout << (areIdentical(root1, root2) ? "true" : "false");64}