|
|
@ -425,3 +425,62 @@ public class Codec { |
|
|
|
} |
|
|
|
} |
|
|
|
``` |
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#### [28. 对称的二叉树](https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
```java |
|
|
|
|
|
|
|
class Solution { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public boolean isSymmetric(TreeNode root) { |
|
|
|
|
|
|
|
if (root == null) { |
|
|
|
|
|
|
|
return true; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
return helper(root.left, root.right); |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private boolean helper(TreeNode root1, TreeNode root2) { |
|
|
|
|
|
|
|
if (root1 == null && root2 == null) { |
|
|
|
|
|
|
|
return true; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
if (root1 == null || root2 == null) { |
|
|
|
|
|
|
|
return false; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
if (root1.val != root2.val) { |
|
|
|
|
|
|
|
return false; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
return helper(root1.left, root2.right) && helper(root1.right, root2.left); |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
```java |
|
|
|
|
|
|
|
class Solution { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public boolean isSymmetric(TreeNode root) { |
|
|
|
|
|
|
|
if (root == null) { |
|
|
|
|
|
|
|
return true; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
Deque<TreeNode> queue = new LinkedList<>(); |
|
|
|
|
|
|
|
queue.addFirst(root.left); |
|
|
|
|
|
|
|
queue.addLast(root.right); |
|
|
|
|
|
|
|
while (!queue.isEmpty()) { |
|
|
|
|
|
|
|
TreeNode first = queue.removeFirst(); |
|
|
|
|
|
|
|
TreeNode last = queue.removeLast(); |
|
|
|
|
|
|
|
if (first == null && last == null) { |
|
|
|
|
|
|
|
continue; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
if (first == null || last == null) { |
|
|
|
|
|
|
|
return false; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
if (first.val != last.val) { |
|
|
|
|
|
|
|
return false; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
queue.addFirst(first.right); |
|
|
|
|
|
|
|
queue.addFirst(first.left); |
|
|
|
|
|
|
|
queue.addLast(last.left); |
|
|
|
|
|
|
|
queue.addLast(last.right); |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
return true; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
``` |
|
|
|
|
|
|
|
|
|
|
|