forked from prakashshuklahub/Interview-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path101 Symmetric Tree
More file actions
46 lines (31 loc) · 1022 Bytes
/
101 Symmetric Tree
File metadata and controls
46 lines (31 loc) · 1022 Bytes
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
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
public boolean isSymmetric(TreeNode root) {
return mirror(root,root);
}
boolean mirror(TreeNode a, TreeNode b){
if(a==null && b==null) return true;
else if(a==null || b==null) return false;
else if(a.val != b.val) return false;
else{
return mirror(a.left,b.right) && mirror(a.right,b.left);
//true && true = true
//false && true = false
//false && false = false
}
}
//Approach
1 //COPY
/ \
2 2 (left = right)
/ \ / \
3 4 4 3 (left = right)
//Case1 a== null && b==null true
//Case2 a==null || b==null false
//Case3 a.val != b.val false
//-------------MOVE-------------