对称二叉树的实现
力扣 101添加链接描述
思考
- 把一颗树拆分为 根、左子树p、右子树q;
- 根为空 对称返回true
- 判断值是否相等&&左树左子叶 == 右数右子叶 && 左树右子叶 == 右树左子叶, 返回true;
- 左树 空&& 右树 空,返回true;
- 左树空 || 右树空 ,返回false;
例如:
- 代码部分
public boolean isSymmetric(TreeNode root) {
if (root == null){
return true;
}
return isMirror(root.left, root.right);
}
private boolean isMirror(TreeNode p,TreeNode q) {
if ( p == null&& q==null){
return true;
}
else if (p==null || q==null){
return false;
}
return p.val==q.val && isMirror(p.left,q.right) && isMirror(p.right,q.left);
}