简体   繁体   中英

Any connection between mirroring a binary tree and blocking queue in Java

I believe mirroring a binary tree is straight-forward in Java like:

 http://stackoverflow.com/questions/4366251/mirror-image-of-a-binary-tree

However, I met with an interview question that relates this problem with the multithreading in Java,ie, blocking queue(java.util.concurrent)

To the best of my knowledge, I don't see an apparent connection between the two concepts, could anybody give me a hint that I might be missing something? Thanks!

In General

The recursive structure of tree mirroring reveals the solution. First given the root node, we swap the left child with the right child on the main thread. Now we apply mirror on the left node and mirror on the right node. But mirroring the left node is independent of mirroring the right node, so we can do them on separate threads.

Keep the following rules in order to avoid having too many threads. The current thread swaps the left and right child of the node it is currently operating on. Then it delegates mirroring of the new left child to a new thread, and proceeds to handle the mirroring of the right node.

Note that for each node we encounter we are spawning a new thread. So if the tree is unbalanced and only has left children, we spawn O(n) threads where n is the number of nodes in the tree. However, we can maintain a thread pool so that once any thread reaches a leaf node it returns to the pool. If the tree is balanced, every thread terminates in O(log n) steps, so we have on the order of O(n / log n) threads (I think?).

Use of a Blocking Queue

You can use the blocking queue in conjunction with this thread pool idea, by placing the left and right nodes once swapped into the Queue, then workers can just take them out and process them, and subsequently return the new left and right children of that subnode back into the queue for another thread to handle. Once a leaf node is hit, there are no left and right children, so nothing is put in the Queue. When the Queue is empty, the mirroring is complete.

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