給定一個二叉樹,檢查它是否是鏡像對稱的。
例如,二叉樹 [1,2,2,3,4,4,3] 是對稱的。
1
/
2 2
/ \ /
3 4 4 3
但是下面這個 [1,2,2,null,3,null,3] 則不是鏡像對稱的:
1
/
2 2
\
3 3
說明:
如果你可以運用遞歸和迭代兩種方法解決這個問題,會很加分。
/**
* 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 isSymmetric(root,root);
}
public boolean isSymmetric(TreeNode root1,TreeNode root2) {
if(root1==null&&root2==null) return true;
if(root1==null||root2==null) return false;
if(root1.val==root2.val
&&isSymmetric(root1.left,root2.right)
&&isSymmetric(root1.right,root2.left)) return true;
return false;
}
}