What is Symmetric Tree
A tree is symmetric when its left side is a mirror of its right side. The outside children must match each other, and the inside children must match each other.
1 2 2 3 4 4 3 yes
Approach
Compare the root's left child with its right child. Then compare the outer pair and the inner pair, and keep going.
The picture highlights the pair being compared. A mismatch stops the search.
Interactive solution
The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each node is compared once. |
| Call stack | O(h) | The mirror walk follows the height. |
Implementation
def mirror(a, b):
if not a and not b:
return True
if not a or not b or a.val != b.val:
return False
return mirror(a.left, b.right) and mirror(a.right, b.left)
def solve(self, root):
return mirror(root.left, root.right)