Problem Description
Given the root of a binary tree, determine if the tree is a mirror of itself (i.e., symmetric around its center). In other words, check if the left subtree is a mirror reflection of the right subtree.
Key Insights
- Use recursion (or iteration) to compare pairs of nodes.
- For two trees (or two nodes) to be mirror images:
- Their root values must be the same.
- The left subtree of one must match the right subtree of the other.
- The right subtree of one must match the left subtree of the other.
- Alternatively, iterative approaches using a queue can be applied to compare the nodes in pairs.
Space and Time Complexity
Time Complexity: O(n), where n is the number of nodes in the tree, since we traverse each node once. Space Complexity: O(h) for recursive call stack (worst-case O(n) for a skewed tree) or O(n) for the iterative approach using a queue.
Solution
We solve the problem using recursion by defining a helper function that takes two nodes and checks if they are mirrors of each other. The helper function:
- Returns true if both nodes are null.
- Returns false if one node is null or if their values differ.
- Recursively compares the left child of the first node with the right child of the second node, and vice-versa. This method ensures each comparison verifies symmetry at every level. A similar logic can be applied iteratively by using a queue to compare pairs of nodes.