难度简单882
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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递归终止条件 当都是空指针 说明两者相等。 如果一个为null 一个不为null 说明两者不等返回false
递归去判断A的左子树和B的右子树 以及 A的右子树和B的左子树。其中短路与的作用决定如果一个子树不对称,那么整颗树是不对称的。
public boolean isSymmetric(TreeNode root) { return isMirror(root,root); } public boolean isMirror(TreeNode root1,TreeNode root2){ if(root1 == null && root2 == null){ return true; } if(root1 == null || root2 == null){ return false; } return (root1.val == root2.val) && isMirror(root1.left,root2.right) && isMirror(root1.right,root2.left); }