File tree Expand file tree Collapse file tree 1 file changed +20
-21
lines changed Expand file tree Collapse file tree 1 file changed +20
-21
lines changed Original file line number Diff line number Diff line change 1
-
2
-
3
- import java .util .ArrayList ;
1
+ import java .util .Stack ;
4
2
5
3
/**
6
4
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
25
23
26
24
public class SymmetricTree {
27
25
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 ) {
36
40
return false ;
41
+ } else {
42
+ s1 .push (n1 .left );
43
+ s1 .push (n1 .right );
44
+ s2 .push (n2 .right );
45
+ s2 .push (n2 .left );
37
46
}
38
47
}
39
48
return true ;
40
49
}
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
- }
51
50
}
You can’t perform that action at this time.
0 commit comments