题目:
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.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
思路:
本题使用了一种很普通的方法,即,先镜像得到镜像后的tree1,然后将原来的tree跟当前tree1进行比较。
如果相同则为真,否则为假。
AC代码:
<pre name="code" class="java">public class Symmetric_Tree {
private void mirrorSelf(TreeNode root){
if(root==null)
return;
TreeNode left = root.left;
root.left = root.right;
root.right = left;
mirrorSelf(root.left);
mirrorSelf(root.right);
}
private void copy(TreeNode newRoot, TreeNode src){
if(src!=null){
TreeNode leftSrc = src.left;
TreeNode rightSrc = src.right;
if(leftSrc!=null){
newRoot.left = new TreeNode(leftSrc.val);
copy(newRoot.left,src.left);
}
if(rightSrc!=null){
newRoot.right = new TreeNode(rightSrc.val);
copy(newRoot.right, src.right);
}
}
}
private boolean equal(TreeNode src, TreeNode src2){
if(src==null && src2==null)
return true;
if(src!=null && src2!=null){
if(src.val==src2.val){
return equal(src.left,src2.left) && equal(src.right, src2.right);
}
}
return false;
}
public boolean isSymmetric(TreeNode root) {
if(root==null)
return true;
TreeNode src = new TreeNode(root.val);
copy(src,root);
mirrorSelf(root);
return equal(src,root);
}
}