Skip to content

Commit 6aab717

Browse files
committed
refine
1 parent 5ffaaa7 commit 6aab717

File tree

1 file changed

+20
-21
lines changed

1 file changed

+20
-21
lines changed

SymmetricTree.java

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
2-
3-
import java.util.ArrayList;
1+
import java.util.Stack;
42

53
/**
64
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
@@ -25,27 +23,28 @@
2523

2624
public class SymmetricTree {
2725
public boolean isSymmetric(TreeNode root) {
28-
ArrayList<String> inOrder = new ArrayList<String>();
29-
inOrder(root, inOrder);
30-
int start = 0, end = inOrder.size() - 1;
31-
while (start < end) {
32-
if (inOrder.get(start).equals(inOrder.get(end))) {
33-
start++;
34-
end--;
35-
} else {
26+
if (root == null)
27+
return true;
28+
Stack<TreeNode> s1 = new Stack<TreeNode>();
29+
Stack<TreeNode> s2 = new Stack<TreeNode>();
30+
s1.push(root.left);
31+
s2.push(root.right);
32+
while (!s1.isEmpty() && !s2.isEmpty()) {
33+
TreeNode n1 = s1.pop();
34+
TreeNode n2 = s2.pop();
35+
if (n1 == null && n2 == null) {
36+
continue;
37+
} else if (n1 == null || n2 == null) {
38+
return false;
39+
} else if (n1.val != n2.val) {
3640
return false;
41+
} else {
42+
s1.push(n1.left);
43+
s1.push(n1.right);
44+
s2.push(n2.right);
45+
s2.push(n2.left);
3746
}
3847
}
3948
return true;
4049
}
41-
42-
public void inOrder(TreeNode root, ArrayList<String> inOrder) {
43-
if (root == null) {
44-
inOrder.add("#");
45-
return;
46-
}
47-
inOrder(root.left, inOrder);
48-
inOrder.add(root.val + "");
49-
inOrder(root.right, inOrder);
50-
}
5150
}

0 commit comments

Comments
 (0)