-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathIsSymmetric.java
46 lines (37 loc) · 1.25 KB
/
IsSymmetric.java
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
package Algorithms;
import java.util.ArrayDeque;
public class IsSymmetric {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
if (root.left == null && root.right == null) {
return true;
} else if (root.left == null || root.right == null) {
return false;
}
// left and right are both not null
ArrayDeque<TreeNode> queueL = new ArrayDeque<TreeNode>();
ArrayDeque<TreeNode> queueR = new ArrayDeque<TreeNode>();
queueL.offer(root.left);
queueR.offer(root.right);
int num = 1;
while (num != 0) {
TreeNode l = queueL.poll();
TreeNode r = queueR.poll();
if (l != null && r != null) { // if they are all not null
if (l.val != r.val) {
return false;
}
queueL.offer(l.left);
queueL.offer(l.right);
queueR.offer(r.right);
queueR.offer(r.left);
num += 4;
} else if (l == null || r == null) {
return false;
}
}
return true;
}
}