Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
先搞recursive的吧,感觉简单一点。
给定两个节点,判断是否对称的条件是:
两个节点值相等;
left的left child等于right的right child;
left的right child等于right的left child.
然后递归判断(left.left, right.right)和(left.right, right.left)
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
return isSymmetric(root.left, root.right);
}
public boolean isSymmetric(TreeNode left, TreeNode right){
if(left == null && right == null)
return true;
if((left == null && right != null) || (left != null && right == null))
return false;
if(left.val != right.val)
return false;
return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
}
}
Now comes the non-recursive version. The basic idea is to perform an altered version of level-order traversal. Each time we retrieve two elements from the queue and perform a similar judgement of the recursive one.
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
if(root.left == null && root.right == null)
return true;
if(root.left == null && root.right != null)
return false;;
if(root.left != null && root.right == null)
return false;
//make a queue to perform an altered version of level-order traversal
LinkedList<TreeNode> q = new LinkedList<TreeNode>();
q.addLast(root.left);
q.addLast(root.right);
while(q.size() >= 2){
TreeNode left = q.pollFirst();
TreeNode right = q.pollFirst();
if(left.val != right.val)
return false;
if((left.left == null && right.right != null) || (left.left != null && right.right == null))
return false;
if((left.right == null && right.left != null) || (left.right != null && right.left == null))
return false;
if(left.left != null && right.right != null){
q.addLast(left.left);
q.addLast(right.right);
}
if(left.right != null && right.left != null){
q.addLast(left.right);
q.addLast(right.left);
}
}
return true;
}
}