-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrees-Structurally identical
57 lines (42 loc) · 1.49 KB
/
Trees-Structurally identical
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Given two Generic trees, return true if they are structurally identical i.e. they are made of nodes with the same values arranged in the same way.
Input format :
Line 1 : Tree 1 elements in level order form separated by space (as per done in class). Order is -
Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element
Line 2 : Tree 2 elements in level order form separated by space (as per done in class). Order is -
Root_data, n (No_Of_Child_Of_Root), n children, and so on for every element
Output format : true or false
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
********************************Solution********************************
import java.util.*;
public static boolean checkIdentical(TreeNode<Integer> root1, TreeNode<Integer> root2){
ArrayList<Integer> temp=new ArrayList<>();
temp=storeNode(root1,temp);
ArrayList<Integer> temp1=new ArrayList<>();
temp1=storeNode(root2,temp1);
if(temp.size()>temp1.size() || temp.size()<temp1.size())
return false;
else{
for(int i=0;i<temp.size();i++)
{
if(temp.get(i)!=temp1.get(i))
return false;
}
return true;
}
}
private static ArrayList<Integer> storeNode(TreeNode<Integer> root, ArrayList<Integer> temp)
{
temp.add(root.data);
for(int i=0;i<root.children.size();i++)
storeNode(root.children.get(i), temp);
return temp;
}