-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSymmetric Tree.java
35 lines (35 loc) · 1.09 KB
/
Symmetric Tree.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<TreeNode> leftList = new ArrayList<TreeNode>();
List<TreeNode> rightList = new ArrayList<TreeNode>();
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
leftList.add(root.left);
rightList.add(root.right);
while(!leftList.isEmpty() && !rightList.isEmpty()) {
TreeNode left = leftList.remove(0);
TreeNode right = rightList.remove(0);
if (left == null && right == null) {
continue;
} else if (left != null && right != null && left.val == right.val) {
leftList.add(left.left);
leftList.add(left.right);
rightList.add(right.right);
rightList.add(right.left);
} else {
return false;
}
}
return leftList.isEmpty() && rightList.isEmpty();
}
}