Given a binary tree, check whether it is mirrored along a line that runs across the root.
By drawing an example we can deduce what is the recursion to apply:
1
2 2
4 3 3 4
We notice that a single node is always mirrored. Given two nodes, children of nodes at a previous level, they are mirrored only if they have the same value and their subtrees are identical, but swapped left and right.
We can do this recursively in O(N) time and space.
You can check my implementation of isMirrored on my Gist along with some tests in IsMirrorJTests.
No comments:
Post a Comment
With great power comes great responsibility