对称树算法(反转+同树)

时间:2017-10-26 18:36:01

标签: tree

给定二叉树,检查它是否是自身的镜像(即,围绕其中心对称)。

这是关于Leetcode的一个问题。我所做的是反转树,然后比较反转树是否与原始树相同。但我无法通过测试用例。我的代码如下,有人可以给我任何建议吗?感谢。

class Solution(object):

def isSymmetric(self, root):
    node = self.invert(root)
    def dfs(root, node):
        if not root and not node:
            return True
        if not root or not node:
            return False
        if root.val == node.val and dfs(root.left, node.left) and dfs(root.right, node.right):
            return True
        else:
            return False

    return dfs(root, node)


def invert(self, node):
    if node:
        node.left, node.right = self.invert(node.right), self.invert(node.left)
    return node

1 个答案:

答案 0 :(得分:0)

反转和验证看起来很多工作。您可以尝试打印树并跟踪每一步的返回值。我的猜测是它没有时间,因为它有额外的操作。

或者

您可以通过树递归并检查每个节点的左右匹配。

示例:

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [io.project.application.SpringConfig]; nested exception is java.lang.IllegalStateException: Failed to introspect annotated methods on class org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:616) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:299) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:245) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:606) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at 
相关问题