I feel this is too hard and unlikely to come up in coding interviews. Also, most trees have up-links, so the no-uplink constraint is artificial and unrealistic. In reality, Morris complexity is usually unnecessary.
- http://www.quora.com/Why-does-the-Morris-in-order-traversal-algorithm-have-O-n-time-complexity is detailed.
- https://codeoverflow.wordpress.com/tag/morris-inorder-traversal/ has explanations + full c++ code
- http://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/ has C code
- http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html has concise c code but not simple at all.
- http://n00tc0d3r.blogspot.sg/2013/09/inorder-binary-tree-traversal-with.html has concise java implementation.
–threaded binary tree is the basis of Morris
The Morris algo need to construct the threaded BST, walk and remove the extra links, all without recursion.
- Tip: For my ascending walk, I only add right-up thread link to bring me to my ancestors. I don’t need any leftward thread link.
- Tip: All the thread links point upward
- How many right-up links? Let’s define two clubs Honey and White.
- every node HH having a left child will get a incoming right-up link pointing to it! After printing HH’s left subtree, this link is used to revisit HH.
- Except the very last node, every node WW without a right child needs to add a right-up link, so we don’t get stuck at WW.
- If the Honey club has H members, and White club has W members, then I think we create H right-up links. W +1 = H
- A node can be both Honey and White i.e. it has a right-up link and is also target of a right-up link.
- Tip: the sequence of Honey nodes to try has to be top-down. We must create the uplink to every higher Honey node first, as insurance that we can always come back. While a higher Honey node is locked down and we search for its predecessor in its left subtree, we ignore any lower Honey node
- First time we hit a Honey node, I’m sure it is not uplinked. After we get it uplinked, we must descend Left.
- 2nd time we hit a Honey node, I believe its left subtree is completely fixed, so if we descend left again, we will go to a dead end. We must move right, either down or up.
- Tip: should really use a few variables instead of “cur”. This “cur” is like a “temp1” variable used in first pass, then temp2 variable in 2nd pass etc. These variables are not related at all.
https://github.com/tiger40490/repo1/blob/cpp1/cpp1/binTree/MorrisInOrder.cpp is my c++ implementation with a concise/cryptic implementation and an “unfolded” elaborate implementation