1) Given 2 arrays containing elements of a complete Binary tree(level by level), without actually reconstructing a tree(i.e. by only doing swaps in an array), how can I find whether those 2 arrays are isomorphic or not ?
2) A better solution if one isomorphic tree forms a Binary Search Tree.
update e.g.
5
/ \
4 7
/\ /\
2 3 6 8
can be represented in array as 5 4 7 2 3 6 8
Isomorphic trees are trees which can be converted to one another by rotation about nodes
5
/ \
4 7
/\ /\
2 3 6 8
5
/ \
4 7
/\ /\
3 2 6 8
5
/ \
4 7
/\ /\
3 2 8 6
5
/ \
7 4
/\ /\
8 6 3 2
For the first problem:
A bit of notation:
t1andt2are isomorphic, ifft1andt2are empty,or
value (t1) == value (t2)and
either
left(t1)is isomorphic toleft(t2)andright(t1)is isomorphic toright(t2),or
left(t1)is isomorphic toright(t2)andright(t1)is isomorphic toleft(t2)Assuming the trees are stored in an arrays, such that element 0 is the root and and if
tis an index of an internal node2t+1and2t+2are indices of its immediate children, straightforward implementation:For the second problem, at each step, we compare the subtree of
awith the smaller root to the subtree ofbwith the smaller root and then the subtree ofawith the bigger root to the subtree ofbwith the bigger root (smaller and bigger than the current roots ofaandb).