« 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;
5
6template <typename T>
7class TreeNode {
8 public:
9 T data;
10 vector<TreeNode<T>*> children;
11
12 TreeNode(T data) { this->data = data; }
13
14 ~TreeNode() {
15 for (int i = 0; i < children.size(); i++) {
16 delete children[i];
17 }
18 }
19};
20
21bool areIdentical(TreeNode<int> *root1, TreeNode<int> * root2) {
22 // Write your code here
23 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}
34
35TreeNode<int>* takeInputLevelWise() {
36 int rootData;
37 cin >> rootData;
38 TreeNode<int>* root = new TreeNode<int>(rootData);
39
40 queue<TreeNode<int>*> pendingNodes;
41
42 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 }
56
57 return root;
58}
59
60int main() {
61 TreeNode<int>* root1 = takeInputLevelWise();
62 TreeNode<int>* root2 = takeInputLevelWise();
63 cout << (areIdentical(root1, root2) ? "true" : "false");
64}