博客
关于我
leetcode-对称二叉树-35
阅读量:273 次
发布时间:2019-03-01

本文共 891 字,大约阅读时间需要 2 分钟。

题目要求

给定一个二叉树,检查它是否是镜像对称的。例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

思路

判断一个二叉树是否镜像对称,可以采用递归的方法。首先检查树的基本情况:如果树为空,则为对称;如果树只有一个根节点,也是对称。如果左子树和右子树均为空,那么是对称的。如果左子树和右子树都不是空,则需要比较它们的值是否相同。如果值不相同,则树不对称。接下来,递归检查左子树和右子树的左、右子树是否对称,以及左右子树交换位置后是否仍对称。

图解

以下是镜像对称二叉树的示意图。左子树和右子树的结构应完全镜像对称,左右节点值对应相等。这意味着左子树的左对应右子树的右,左子树的右对应右子树的左。

代码实现

bool dfs(TreeNode* left, TreeNode* right) {    if (left == NULL && right == NULL) {        return true;    }    if (left == NULL || right == NULL) {        return false;    }    if (left->val != right->val) {        return false;    }    return dfs(left->left, right->right) &&           dfs(left->right, right->left);}bool isSymmetric(TreeNode* root) {    if (root == NULL || (root->left == NULL && root->right == NULL)) {        return true;    }    return dfs(root->left, root->right);}

以上代码实现了对镜像对称二叉树的高效检查。通过递归比较左右子树的值以及它们的左右子树,确保整个树的镜像对称性。这个方法的时间复杂度为 O(h),其中 h 是树的高度,空间复杂度为 O(1)。

转载地址:http://xjno.baihongyu.com/

你可能感兴趣的文章
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>