101.SymmetricTree

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

十余年的广水网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。成都全网营销的优势是能够根据用户设备显示端的尺寸不同,自动调整广水建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联从事“广水网站设计”,“广水网站推广”以来,每个客户项目都认真落实执行。

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);
    }

文章题目:101.SymmetricTree
标题链接:http://pwwzsj.com/article/igscsd.html