File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ ``` java
2
+ // 递归
3
+ /**
4
+ * Definition for a binary tree node.
5
+ * public class TreeNode {
6
+ * int val;
7
+ * TreeNode left;
8
+ * TreeNode right;
9
+ * TreeNode(int x) { val = x; }
10
+ * }
11
+ */
12
+ class Solution {
13
+ public boolean isSymmetric (TreeNode root ) {
14
+ return root == null || isSymmetric(root. left, root. right);
15
+ }
16
+
17
+ public boolean isSymmetric (TreeNode left , TreeNode right ) {
18
+ if (left == null || right == null ) {
19
+ return left == right;
20
+ }
21
+ return left. val == right. val && isSymmetric(left. left, right. right) && isSymmetric(left. right, right. left);
22
+ }
23
+ }
24
+
25
+ // 迭代
26
+ /**
27
+ * Definition for a binary tree node.
28
+ * public class TreeNode {
29
+ * int val;
30
+ * TreeNode left;
31
+ * TreeNode right;
32
+ * TreeNode(int x) { val = x; }
33
+ * }
34
+ */
35
+ class Solution {
36
+ public boolean isSymmetric (TreeNode root ) {
37
+ if (root == null ) {
38
+ return true ;
39
+ }
40
+ LinkedList<TreeNode > stack = new LinkedList<> ();
41
+ stack. push(root. left);
42
+ stack. push(root. right);
43
+ while (! stack. isEmpty()) {
44
+ TreeNode right = stack. pop();
45
+ TreeNode left = stack. pop();
46
+ if (left == null && right == null ) {
47
+ continue ;
48
+ }
49
+ if (left == null || right == null ) {
50
+ return false ;
51
+ }
52
+ if (left. val != right. val) {
53
+ return false ;
54
+ }
55
+ stack. push(left. left);
56
+ stack. push(right. right);
57
+ stack. push(left. right);
58
+ stack. push(right. left);
59
+ }
60
+ return true ;
61
+ }
62
+ }
63
+ ```
You can’t perform that action at this time.
0 commit comments