-
Notifications
You must be signed in to change notification settings - Fork 0
/
101. Symmetric Tree.java
47 lines (41 loc) · 1.19 KB
/
101. 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
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>();
s1.push(root); s2.push(root);
TreeNode right = root;
TreeNode left = root;
while(!s1.isEmpty() && !s2.isEmpty()) {
right = s1.pop();
left = s2.pop();
if(right != null) {
if(left == null)
return false;
else if(right.val != left.val)
return false;
}else {
if(left != null)
return false;
}
if(right != null) {
s1.push(right.left);
s1.push(right.right);
}
if(left != null) {
s2.push(left.right);
s2.push(left.left);
}
}
return true;
}
}