给定一棵二叉树,判断其是否是自身的镜像(即:是否对称)
方法一:递归
class Solution {
public:
bool isduicheng (TreeNode* root1,TreeNode* root2){
if(!root1 && !root2) return true;
if(!root1 || !root2) return false;
return (root1->val == root2->val) && (isduicheng(root1->left, root2->right))
&& (isduicheng(root1->right, root2->left));
}
bool isSymmetrical(TreeNode* pRoot) {
if(!pRoot) return true;
return isduicheng(pRoot->left, pRoot->right);
}
};
终止条件就是左右节点其中一个为空,说明到了一个叶子节点,如果两边都为空,则返回true,如果只有一个为空则返回false。