如何检查二叉树的结构不是值是否具有镜像对称性

问题描述

我被要求编写一个递归算法来检查二叉树的结构(不是值)是否具有镜像对称性。例如:

        1
       / \
      /   \
     /     \
     3      5
    / \    / \
    7  9  11 13
       /   \
      15   17

具有对称结构。我很感激专家的眼光来帮助我。提前致谢。 我知道如何检查值是否对称但不是实际结构。

解决方法

假设您有一个具有 Nodeleft 属性的 right 类,所需的函数在 Python 中可能如下所示:

def is_mirror(left,right):
    if left is None or right is None:  # Either one is None
        return left == right  # True when both are None
    return is_mirror(left.left,right.right) and is_mirror(left.right,right.left)

你可以这样称呼它:

# Create the example tree from the question:
tree = Node(1,Node(3,Node(7),Node(9,Node(15)
        )
    ),Node(5,Node(11,None,Node(17)
        ),Node(13)
    )
)

print(is_mirror(tree.left,tree.right))  # True

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...