Morris Inorder Traversal
Get startedজয় শ্রী রাম
🕉Prerequisite:
The concept of Morris Inorder Traversal is explained in the video below. It is highly recommended that you please read the chapter on Threaded Binary Tree first, if you already haven't done so, and then watch the video for a better understanding. Please excuse my speech impediment while watching the video. Thank you for your patience.
Working Code:
Java code:
Login to Access Content
Python code:
Login to Access Content
Further Optimization:
The above implementation has a major problem:
- We are modifying the right child pointer of the leaf nodes but never recovering them. This results in side-effects which are not desired in a Clean Code, unless and until we are explicitly told that side-effect is fine as per the given requirements. we are told that
We will be solving the above mentioned problem in the code below. Every time we visit a node we will compute it's inorder predecessor and check whether the right child pointer of the predecessor is null or already point to the current node. If it is already pointing to the current node that means it is the second visit and we recover the modified right child pointer by pointing it back to null. When we visit a node for the first time we just compute the predecessor and modify the predecessor's right child pointer so that we can come back to the current node to visit it once the left subtree of the current node is entirely processed. In our second visit to the a node we actually visit it and process it.
Java code:
Login to Access Content
Python code:
Login to Access Content