(1)代码
方法一:递归
时间复杂度O(N)
空间复杂度O(N)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return check(root, root);
}
public boolean check(TreeNode p, TreeNode q){
if(p == null && q == null) return true;
if(p == null || q == null) return false;
return p.val == q.val && check(q.left, p.right) && check(q.right, p.left);
}
}
方法二:迭代
时间复杂度O(N)
空间复杂度O(N)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return check(root, root);
}
public boolean check(TreeNode u, TreeNode v){
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(u);
queue.offer(v);
while(!queue.isEmpty()){
u = queue.poll();
v = queue.poll();
if(u == null && v == null) continue;
if((u == null || v == null) || (u.val != v.val)) return false;
queue.offer(u.left);
queue.offer(v.right);
queue.offer(u.right);
queue.offer(v.left);
}
return true;
}
}