博客
关于我
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/

你可能感兴趣的文章
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>