-
Notifications
You must be signed in to change notification settings - Fork 4
/
SymmetricTree.java
47 lines (41 loc) · 1.3 KB
/
SymmetricTree.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
47
package com.dbc;
import java.util.*;
public class SymmetricTree {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public boolean isSymmetric(TreeNode root) {
List<TreeNode> queue = new ArrayList<>();
queue.add(root);
while (!queue.isEmpty()) {
int length = queue.size();
int left = 0, right = length - 1;
while (left < right) {
if ((queue.get(left) == null && queue.get(right) != null) || (queue.get(left) != null && queue.get(right) == null)) return false;
if (queue.get(left) != null && queue.get(right) != null && queue.get(left).val != queue.get(right).val) return false;
left++;
right--;
}
for (int i = 0; i < length; i++) {
TreeNode node = queue.remove(0);
if (node != null) {
queue.add(node.left);
queue.add(node.right);
}
}
}
return true;
}
}