1
+ import java .util .LinkedList ;
2
+ import java .util .Queue ;
3
+ import java .util .Stack ;
4
+
1
5
public class SymmetricTree {
2
6
3
7
public boolean isSymmetric (TreeNode root ) {
@@ -16,4 +20,72 @@ private boolean isSymmetric(TreeNode left, TreeNode right) {
16
20
}
17
21
return left .val == right .val && isSymmetric (left .left , right .right ) && isSymmetric (left .right , right .left );
18
22
}
23
+
24
+ public boolean isSymmetric2 (TreeNode root ) {
25
+ if (root == null ) {
26
+ return true ;
27
+ }
28
+ Queue <TreeNode > queue1 = new LinkedList <>();
29
+ Queue <TreeNode > queue2 = new LinkedList <>();
30
+ queue1 .offer (root .left );
31
+ queue2 .offer (root .right );
32
+ while (!queue1 .isEmpty () && !queue2 .isEmpty ()) {
33
+ TreeNode left = queue1 .poll ();
34
+ TreeNode right = queue2 .poll ();
35
+ if (left == null && right == null ) {
36
+ continue ;
37
+ }
38
+ if (left == null || right == null ) {
39
+ return false ;
40
+ }
41
+ if (left .val != right .val ) {
42
+ return false ;
43
+ }
44
+ queue1 .offer (left .left );
45
+ queue1 .offer (left .right );
46
+ queue2 .offer (right .right );
47
+ queue2 .offer (right .left );
48
+ }
49
+ return queue1 .isEmpty () && queue2 .isEmpty ();
50
+ }
51
+
52
+ /**
53
+ * 非递归写法
54
+ */
55
+ public boolean isSymmetric2 (TreeNode left , TreeNode right ) {
56
+ if (left == null && right == null ) {
57
+ return true ;
58
+ }
59
+ if (left == null || right == null ) {
60
+ return false ;
61
+ }
62
+
63
+ Stack <TreeNode > stack1 = new Stack <TreeNode >();
64
+ Stack <TreeNode > stack2 = new Stack <TreeNode >();
65
+
66
+ while (!stack1 .isEmpty () || left != null ) {
67
+ if (left != null ) {
68
+ if (right == null ) {
69
+ return false ;
70
+ }
71
+ if (left .val != right .val ) {
72
+ return false ;
73
+ }
74
+ stack1 .push (left );
75
+ stack2 .push (right );
76
+ left = left .left ;
77
+ right = right .right ;
78
+ } else {
79
+ if (right != null ) {
80
+ return false ;
81
+ }
82
+ if (stack2 .isEmpty ()) {
83
+ return false ;
84
+ }
85
+ left = stack1 .pop ().right ;
86
+ right = stack2 .pop ().left ;
87
+ }
88
+ }
89
+ return stack2 .isEmpty () && right == null ;
90
+ }
19
91
}
0 commit comments