0
votes

How to check whether two complete binary trees are mirror of each other where only the level order traversal of the trees are given ?

A Complete binary tree is a binary tree which all the nodes except the leaf nodes have 2 child nodes.

2
What do you think yourself?Bart Kiers
What i thought is first compare the root element, If they are equal then compare the next two elements (f1, f2) with (s2, s1) in the level order traversal . If they are equal then move on two the next two elements. the numbers represent which is first and second.Tippis

2 Answers

4
votes

I don't think this is possible. Consider these two trees:

   0              0
  / \          /     \
 1   2        1       2
    / \      / \     / \
   3   4    3   4   5   6
  / \
 5   6

These are complete binary trees (according to your definition), and even though they're different trees they have the same level-order traversals: 0123456.

Now, look at their mirrors:

    0              0
   / \          /     \
  2   1        2       1
 / \          / \     / \
4   3        6   5   4   3
   / \
  6   5

Notice that the left tree has level-order traversal 0214365, while the right tree has level-order traversal 0216543. In other words, the original trees have the same level order traversals, but their mirrors have different traversals.

Now, think about what happens if you have your algorithm and you feed in 0123456 (the level-order traversal of either of the trees) and 0214365 (the level-order traversal of one of the mirrors). What can the algorithm say? If it says that they're mirrors, it will be wrong if you fed in the second of the input trees. If it says that they're not mirrors, it will be wrong if you fed in the first of the input trees. Therefore, there's no way for the algorithm to always produce the right answer.

Hope this helps!

0
votes

According to general definitions, in a complete binary tree, every level except possibly the last, is completely filled, and all nodes are as far left as possible. So a complete binary tree may have a node with just one child (for eg, one root node with one left child is a complete binary tree). A tree where all nodes except the leaves have 2 child nodes is called a full binary tree.

For complete binary trees, the problem would be trivial. Starting from the top-down, for the ith level you need to compare 2^i elements (root being the 0th level) of the given level-order traversals A and B. For any given i, the set of 2^i elements from A should be equal to the reverse of these elements from B. However, the last level may not be completely filled and you'll need to account for that.

For full binary trees, where the only constraint given is that every node has 2 or no children, it won't be possible unless you have constructed the tree itself. And you cannot construct a tree by using only level-order traversal. templatetypedef provides a good example.