101. Symmetric Tree

本文介绍了两种判断二叉树是否对称的方法:递归法和队列法。递归法通过比较二叉树的左子树和右子树是否为镜像来判断,而队列法则使用队列存储节点,逐层比较左右子树节点的值是否相等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python:

# 方法一 递归
class Solution1:
    def isSymmetric(self, root):
        if not root:                                 # 先判断根节点是否为空
            return True
        return self.isMirror(root.left, root.right)  # 分成左子树和右子树判断

    def isMirror(self, p, q):                        # 判断两棵树是否是镜像树
        if not p and not q:                          # 根节点都为空,是
            return True
        if not p or not q:                           # 其中有一棵为空,不是
            return False
        l = self.isMirror(p.left, q.right)           # p的左子树和q的右子树是否相同
        r = self.isMirror(p.right, q.left)           # p的右子树和q的左子树是否相同
        return p.val == q.val and l and r            # 值相等,并且p的左=q的右,p的右=q的左

# 方法二 队列实现
class Solution:
    def isSymmetric(self, root):
        """
        队列
        :param root:
        :return:
        """

        if not root:
            return True

        node_queue = [root.left, root.right]  # 在空队列中加入左子树和右子树

        while node_queue:
            left = node_queue.pop(0)          # 依次弹出两个元素
            right = node_queue.pop(0)

            if not right and not left:        # 如果均为空,继续下一个循环
                continue
            if not right or not left:         # 如果只有一个为空,返回False
                return False

            if left.val != right.val:         # 都非空,再判断值是否相等
                return False

            node_queue.append(left.left)      # 将两个左右子树的左右子树逆序加入队列
            node_queue.append(right.right)
            node_queue.append(left.right)
            node_queue.append(right.left)
            #node_queue.extend([left.left, right.right, left.right, right.left])   或者用这一句话写

        return True

C++:

bool isSymmetric(TreeNode* root) {
        TreeNode* l=NULL;
        TreeNode* r=NULL;
        if(!root)
            return true;
        queue<TreeNode*> q;
        q.push(root->left);
        q.push(root->right);
        while(!q.empty())
        {
            l=q.front();
            q.pop();
            r=q.front();
            q.pop();
            if(!l&&!r)
                continue;
            if(!l||!r)
                return false;
            if(l->val!=r->val)
                return false;
            q.push(l->left);
            q.push(r->right);
            q.push(l->right);
            q.push(r->left);
        }
        return true;
        
    }
bool isMirror(TreeNode* p,TreeNode* q){
        bool l=false;
        bool r=false;
        if((!p)&&(!q))
            return true;
        if((!p)||(!q))
            return false;
        l=isMirror(p->left,q->right);
        r=isMirror(p->right,q->left);
        return (p->val==q->val)&&l&&r;
    }
    bool isSymmetric(TreeNode* root) {
        if(!root)
		return true;
	    return isMirror(root->left,root->right);
        
    }
执行 java -Djava.security.debug=provider -jar tks-shop-test.jar 报错[traceId:] 2025-06-03T09:48:27.798+08:00 WARN 311663 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tokenAes' defined in class path resource [com/yami/shop/common/config/ShopBeanConfig.class]: Failed to instantiate [cn.hutool.crypto.symmetric.AES]: Factory method 'tokenAes' threw exception with message: SecurityException: JCE cannot authenticate the provider BC [traceId:] 2025-06-03T09:48:27.810+08:00 DEBUG 311663 --- [ main] c.y.s.c.t.TraceThreadPoolTaskExceutor : Shutting down ExecutorService 'taskExecutor' [traceId:] 2025-06-03T09:48:27.841+08:00 INFO 311663 --- [lientSelector_1] RocketmqRemoting : closeChannel: close the connection to remote address[47.115.51.7:10911] result: true [traceId:] 2025-06-03T09:48:27.845+08:00 INFO 311663 --- [lientSelector_1] RocketmqRemoting : closeChannel: close the connection to remote address[47.115.51.7:9876] result: true [traceId:] 2025-06-03T09:48:27.911+08:00 INFO 311663 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] [traceId:] 2025-06-03T09:48:27.960+08:00 INFO 311663 --- [ main] .s.b.a.l.ConditionEvaluationReportLogger : Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled. [traceId:] 2025-06-03T09:48:28.016+08:00 ERROR 311663 --- [ main] o.s.boot.SpringApplication : Application run failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tokenAes' defined in class path resource [com/yami/shop/common/config/ShopBeanConfig.class]: Failed to instantiate [cn.hutool.crypto.symmetric.AES]: Factory method 'tokenAes' threw exception with message: SecurityException: JCE cannot authenticate the provider BC at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:659) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:493) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1332) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1162) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:560) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:941) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:608) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) at org.springframework.boot.SpringApplication.run(SpringApplication.java:310) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1304) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1293) at com.yami.shop.admin.WebApplication.main(WebApplication.java:25) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) at org.springframework.boot.loader.Launcher.launch(Launcher.java:95) at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:65) Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [cn.hutool.crypto.symmetric.AES]: Factory method 'tokenAes' threw exception with message: SecurityException: JCE cannot authenticate the provider BC at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:171) at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655) ... 27 common frames omitted Caused by: cn.hutool.crypto.CryptoException: SecurityException: JCE cannot authenticate the provider BC at cn.hutool.crypto.SecureUtil.createCipher(SecureUtil.java:1034) at cn.hutool.crypto.CipherWrapper.<init>(CipherWrapper.java:39) at cn.hutool.crypto.symmetric.SymmetricCrypto.init(SymmetricCrypto.java:150) at cn.hutool.crypto.symmetric.SymmetricCrypto.<init>(SymmetricCrypto.java:127) at cn.hutool.crypto.symmetric.SymmetricCrypto.<init>(SymmetricCrypto.java:115) at cn.hutool.crypto.symmetric.SymmetricCrypto.<init>(SymmetricCrypto.java:104) at cn.hutool.crypto.symmetric.SymmetricCrypto.<init>(SymmetricCrypto.java:83) at cn.hutool.crypto.symmetric.AES.<init>(AES.java:50) at com.yami.shop.common.config.ShopBeanConfig.tokenAes(ShopBeanConfig.java:27) at com.yami.shop.common.config.ShopBeanConfig$$SpringCGLIB$$0.CGLIB$tokenAes$3(<generated>) at com.yami.shop.common.config.ShopBeanConfig$$SpringCGLIB$$2.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:258) at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) at com.yami.shop.common.config.ShopBeanConfig$$SpringCGLIB$$0.tokenAes(<generated>) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:139) ... 28 common frames omitted Caused by: java.lang.SecurityException: JCE cannot authenticate the provider BC at java.base/javax.crypto.Cipher.getInstance(Cipher.java:722) at cn.hutool.crypto.SecureUtil.createCipher(SecureUtil.java:1032) ... 46 common frames omitted Caused by: java.lang.IllegalStateException: zip file closed at java.base/java.util.zip.ZipFile.ensureOpen(ZipFile.java:839) at java.base/java.util.zip.ZipFile.getManifestName(ZipFile.java:1065) at java.base/java.util.zip.ZipFile$1.getManifestName(ZipFile.java:1108) at java.base/javax.crypto.JarVerifier.verifySingleJar(JarVerifier.java:464) at java.base/javax.crypto.JarVerifier.verifyJars(JarVerifier.java:320) at java.base/javax.crypto.JarVerifier.verify(JarVerifier.java:263) at java.base/javax.crypto.ProviderVerifier.verify(ProviderVerifier.java:130) at java.base/javax.crypto.JceSecurity.verifyProvider(JceSecurity.java:190) at java.base/javax.crypto.JceSecurity.getVerificationResult(JceSecurity.java:218) at java.base/javax.crypto.Cipher.getInstance(Cipher.java:718) ... 47 common frames omitted
最新发布
06-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值