101. Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3


But the following is not:

    1
   / \
  2   2
   \   \
   3    3


Note:
Bonus points if you could solve it both recursively and iteratively.

解法一:

递归方法,判断一个二叉树是否为对称二叉树,对非空二叉树,则如果:

左子树的根val和右子树的根val相同,则表示当前层是对称的。需判断下层是否对称,

此时需判断:左子树的左子树的根val和右子树的右子树根val,左子树的右子树根val和右子树的左子树根val,这两种情况的val值是否相等,如果相等,则满足相应层相等,迭代操作直至最后一层。

bool isSame(TreeNode *root1,TreeNode *root2){
        if(!root1&&!root2)//二根都为null,
            return true;
        
        //二根不全为null,且在全部为null时,两者的val不同。
        if(!root1&&root2||root1&&!root2||root1->val!=root2->val)
            return false;
        //判断下一层。
        return isSame(root1->left,root2->right)&&isSame(root1->right,root2->left);
    }
    bool isSymmetric(TreeNode* root) {
        if(!root)
            return true;
        return isSame(root->left,root->right);
    }