简体   繁体   中英

How to check if a binary tree has mirror symmetery in its stucture (not values)

I am asked to write a recursive algorithm which checks if a binary tree has mirror symmetry in its structure (not values). For example:

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

Has symmetrical structure. I would appreciate an expert eye to help me. Thanks in advance. I know how to check if the values are symmetric but not the actual structure.

Assuming you have a class Node with left and right properties, the required function could look like this in 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)

You would call it like this:

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM