An easy trick to derive tree traversal results in a single look
This 3 min read empowers one with a technique to traverse a binary tree in a single look. Practice this impressive method once and keep it handy throughout your life!!
Suppose we have to conduct preorder, inorder and postorder traversals on the tree given in the figure below:
Step 1: Make 3 dots around each node
Make 3 dots around each node as shown in the figure below:
Step 2: Start Snake Crawl
After making the 3 dots, start crawling like a snake around the tree. Start from the left of the root node, crawl around the entire tree and end once you reach its right side. For a better explanation, follow the dashed line that gets drawn around the entire tree in the figure below:
Step 3a: Obtain results for Preorder Traversal
During the snake crawl, when you reach a ‘blue’ colored dot (i.e. a dot that lies on the left of a node), note down the value of that node. The sequence obtained by all these noted values is the result of the Preorder Traversal. For a better explanation, look at the figure below:
Step 3b: Obtain results for Inorder Traversal
During the snake crawl, when you reach a ‘yellow’ colored dot (i.e. a dot that lies at the bottom of a node), note down the value of that node. The sequence obtained by all these noted values is the result of the Inorder Traversal. For a better explanation, look at the figure below:
Step 3c: Obtain results for Postorder Traversal
During the snake crawl, when you reach a ‘green’ colored dot (i.e. a dot that lies at the right of a node), note down the value of that node. The sequence obtained by all these noted values is the result of the Postorder Traversal. For a better explanation, look at the figure below:
Conclusion
In this story we learnt how to look at a binary tree and derive the preorder, inorder and postorder traversal for it.