-3

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.

mohelt
  • 55
  • 2
  • 6
  • Isn’t it just a matter of tracking lefts and rights? – matt Apr 13 '21 at 04:37
  • 1
    One approach is a recursive function with signature `bool isMirrored(struct node *left, struct node *right)` which is called as `bool result = isMirrored(root->left, root->right);` And the general idea is a dual DFS that simultaneously traverses the left and right subtrees. – user3386109 Apr 13 '21 at 04:47
  • 1
    What have you tried? Add current approach/code – Abhinav Mathur Apr 13 '21 at 05:00
  • If you know how to check if the values are symmetric, just assume the values on each node are all zero and do the check – Jacder Zhang Apr 13 '21 at 06:52

1 Answers1

0

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
trincot
  • 317,000
  • 35
  • 244
  • 286