101. Symmetric Tree

发布时间:2020-06-25 19:15:30 作者:qdqade
来源:网络 阅读:395

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


推荐阅读:
  1. leetCode 101. Symmetric Tree 对称树
  2. 在IIS上如何部署ASP.NET Core项目

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

example following whether

上一篇:ButterKnife的安装与使用以及ButterKnife右键不显示的大坑

下一篇:python基础四(模块的导入)

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》