如何解决如何检查二叉树的结构不是值是否具有镜像对称性
我被要求编写一个递归算法来检查二叉树的结构(不是值)是否具有镜像对称性。例如:
1
/ \
/ \
/ \
3 5
/ \ / \
7 9 11 13
/ \
15 17
具有对称结构。我很感激专家的眼光来帮助我。提前致谢。 我知道如何检查值是否对称但不是实际结构。
解决方法
假设您有一个具有 Node
和 left
属性的 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。