Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
方法1:利用递归的方式判断
/**
* 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 isSymmetry(root, root);
}
public boolean isSymmetry(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return (t1.val == t2.val)&& isSymmetry(t1.right, t2.left) && isSymmetry(t1.left, t2.right);
}
}
时间复杂度:O(n)
空间复杂度:O(n)
方法2:利用队列的方式
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);
while (!q.isEmpty()) {
TreeNode t1 = q.poll();
TreeNode t2 = q.poll();
if (t1 == null && t2 == null) continue;
if (t1 == null || t2 == null) return false;
if (t1.val != t2.val) return false;
q.add(t1.left);
q.add(t2.right);
q.add(t1.right);
q.add(t2.left);
}
return true;
}
时间复杂度:O(n)
空间复杂度:O(n)
方法3:把方法2进行了改进下,但是在leetcode上面跑,效率都不如方法2;
/**
* 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 isSymmetry(root,root);
}
public boolean isSymmetry(TreeNode l1,TreeNode l2){
if(l1 == null && l2 == null){
return true;
}else if(l1 == null || l2==null){
return false;
}else{
return (l1.val==l2.val)&&(isSymmetry(l1.left,l2.right))&&(isSymmetry(l1.right,l2.left));
}
}
}
时间复杂度:O(n)
空间复杂度:O(n)