101、对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
class Solution {
public: bool isSymmetric(TreeNode * root) {
if(root==NULL) return true;
return check(root -> left,root -> right);
}
public: bool check(TreeNode * rootLeft,TreeNode * rootRight){
if(rootLeft==NULL&&rootRight==NULL)return true;
if(rootLeft==NULL||rootRight==NULL)return false;
//比较相同位置的值是否相等
if(rootLeft -> val!=rootRight -> val)return false;
//传入左子树的左节点,右子树的右节点
if(!check(rootLeft -> left,rootRight -> right))return false;
//传入左子树的右节点,右子树的左节点
if(!check(rootLeft -> right,rootRight -> left))return false;
return true;
}
};