问题描述:
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
思路:
(1)若根节点不存在,则以其为根的子树不存在,则认为是对称
(2)若根节点存在,且
(1) 左子树和右子树均不存在,认为是对称
(2) 左子树和右子树仅存其一,认为是不对称
(3) 左子树与右子树均存在
(1)值相等, 递归比较
(2)值不相等,则不对称
class Solution {
public boolean isSymmetric(TreeNode root) {
return isMirror(root.left, root.right);
}
public boolean isMirror(TreeNode a, TreeNode b){
if ((a==null)&&(b==null)) return true;
if ((a==null)||(b==null)) return false;
return (a.val==b.val)&& isMirror(a.left, b.right) && isMirror(a.right, b.left);
}
}
时间复杂度:O(N)每个点过一遍