简体   繁体   中英

Given the level order traversal of two complete binary trees, how to check whether one tree is mirror of other?

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.

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM