Morris Traversal (Threaded Binary Tree) šŸš€

beginner
8 min

Morris Traversal (Threaded Binary Tree) šŸš€

Welcome back to CodeYourCraft! Today, we're diving into an interesting topic called Morris Traversal in the context of Threaded Binary Trees. This technique is a powerful tool for traversing binary trees in a specific way, and it's super useful when dealing with data structures in real-world projects. šŸŽÆ

What is a Threaded Binary Tree? šŸ“

A Threaded Binary Tree is an extension of a binary tree, where each node points to its in-order successor and predecessor, in addition to the regular left and right child nodes. This allows for traversal without using stack or recursion, making it more memory-efficient.

Understanding Morris Traversal šŸ’”

Morris Traversal is a non-recursive, in-place algorithm used for visiting all the nodes of a binary tree exactly once in the Inorder traversal. It uses the concept of creating virtual nodes to achieve this.

Here are the main steps of Morris Traversal:

  1. Initialization: Start from the root node. If the root is null, return.

  2. Traverse the Left Subtree: Visit the left child of the current node. If the left child is null, make the right child's in-order successor as the current node.

  3. Process the Current Node: After visiting the left child, process the current node. If the current node is not the right child of its parent, make the current node the right child of its in-order predecessor (i.e., the parent).

  4. Traverse the Right Subtree: Visit the right child of the current node. If the right child is not null, repeat the process from step 2.

  5. Inorder Traversal: After finishing the traversal, perform Inorder traversal by printing the data of each current node.

Let's Implement Morris Traversal āœ…

Now that we've understood the concept, let's implement Morris Traversal in Python. Here's a simple example:

python
class Node: def __init__(self, key): self.left = None self.right = None self.data = key self.right_link = None def MorrisInorder(root): current = root while current is not None: if current.left is None: temp = current current = current.left temp.left = None print(temp.data, end=" ") else: temp = current.left while temp.right is not None and temp.right != current: temp = temp.right if temp.right is None: temp.right = current current = current.left else: print(current.data, end=" ") temp.right = None current = current.right # Test the MorrisInorder function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) MorrisInorder(root) # Output: 4 2 5 3 1
Quick Quiz
Question 1 of 1

What is the purpose of the `right_link` attribute in the Node class?

That's it for today! We've learned about Morris Traversal and Threaded Binary Trees. This technique is a great tool to add to your programming toolkit, especially when dealing with complex data structures. Stay tuned for more exciting lessons here at CodeYourCraft! šŸš€šŸŽ‰