-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCheckIfTreeIsIsomorphic.cpp
56 lines (48 loc) · 1.89 KB
/
CheckIfTreeIsIsomorphic.cpp
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
/*
Given two Binary Trees. Check whether they are Isomorphic or not.
Note:
Two trees are called isomorphic if one can be obtained from another by a series of flips, i.e. by swapping left and right children of several nodes. Any number of nodes at any level can have their children swapped. Two empty trees are isomorphic.
For example, the following two trees are isomorphic with the following sub-trees flipped: 2 and 3, NULL and 6, 7 and 8.
ISomorphicTrees
Example 1:
Input:
T1 1 T2: 1
/ \ / \
2 3 3 2
/ /
4 4
Output: No
Example 2:
Input:
T1 1 T2: 1
/ \ / \
2 3 3 2
/ \
4 4
Output: Yes
Your Task:
You don't need to read input or print anything. Your task is to complete the function isomorphic() that takes the root nodes of both the Binary Trees as its input and returns True if the two trees are isomorphic. Else, it returns False. (The driver code will print Yes if the returned values are true, otherwise false.)
Expected Time Complexity: O(min(M, N)) where M and N are the sizes of the two trees.
Expected Auxiliary Space: O(min(H1, H2)) where H1 and H2 are the heights of the two trees.
*/
/*Complete the function below
Node is as follows:
struct Node {
int data;
Node *left;
Node *right;
Node(int val) {
data = val;
left = right = NULL;
}
};
*/
class Solution{
public:
// Return True if the given trees are isomotphic. Else return False.
bool isIsomorphic(Node *root1,Node *root2)
{
if(!root1 or !root2) return root1==root2;
return (root1->data==root2->data and ((isIsomorphic(root1->left,root2->right) and isIsomorphic(root1->right,root2->left)) or (isIsomorphic(root1->left,root2->left) and isIsomorphic(root1->right,root2->right))));
}
};