All Articles

Morris Traversal

Algorithm

The algorithm restructures a tree in the way that a link is created between a current node and its predecessor(in a BST) during traversal and is removed later.

Preorder: root -> left -> right

  1. Start the traversal with the root node as the current node, go to its left child
  2. if the left child
    • 2.1 does not exist, read the current node and move to its right child.
    • 2.2 does exist, find the rightmost child of this left child. For this rightmost child
      • 2.21 if it has not linked to the current node, let the current node be the right child of this rightmost child and read the current node
      • 2.22 if the link has been made, namely (rightmost child).right == current node, there is a loop and we need to break the loop by removing the link. Now skip the current node (it’s has already been read) and move to its right child for the round (go back to step 1).

Pseduo Code

PreorderWithMorrisTraversal(root)
  Let L be an empty list
  curr := root

  while curr != null
    if curr.left == null
      L.add(curr.val)
      curr = curr.right
    else
      pred = curr.left
      while pred.right != null and pred.right != curr
        pred = pred.right

      if pred.right == null
        L.add(curr.val)
        //1. link the current node to its inorder predecessor
        pred.right = curr
        curr = curr.left
      else
        //2. restore tree structure
        pred.right = null
        curr = curr.right

  return L

Preorder Traversal

Step 1 Step 2 Step 3

%0 Step 2 n22 2 n1 1 n1->n22 n7 7 n1->n7 n2 2 n3 3 n2->n3 n4 4 n2->n4 n5 5 n4->n5 n6 6 n4->n6 n6->n1 %0 Step 3 n22 2 n33 3 n1 1 n1->n22 n7 7 n1->n7 n2 2 n2->n33 n4 4 n2->n4 n3 3 n3->n2 n5 5 n4->n5 n6 6 n4->n6 n6->n1 %0 Step 4 n22 2 n33 3 n1 1 n1->n22 n7 7 n1->n7 n2 2 n2->n33 n4 4 n2->n4 n3 3 n5 5 n4->n5 n6 6 n4->n6 n6->n1 %0 Step 5 n22 2 n1 1 n1->n22 n7 7 n1->n7 n2 2 n3 3 n2->n3 n4 4 n2->n4 n5 5 n4->n5 n6 6 n4->n6 n6->n1 %0 Step 6 n22 2 n1 1 n1->n22 n7 7 n1->n7 n4 4 n5 5 n4->n5 n6 6 n4->n6 n6->n1 %0 Step 7 n22 2 n55 5 n1 1 n1->n22 n7 7 n1->n7 n4 4 n4->n55 n6 6 n4->n6 n5 5 n5->n4 n6->n1 %0 Step 8 n22 2 n1 1 n1->n22 n7 7 n1->n7 n4 4 n5 5 n4->n5 n6 6 n4->n6 n6->n1 %0 Step 9 n22 2 n1 1 n1->n22 n7 7 n1->n7 n4 4 n5 5 n4->n5 n6 6 n4->n6 n6->n1 %0 Step 10 n22 2 n1 1 n1->n22 n7 7 n1->n7 n4 4 n5 5 n4->n5 n6 6 n4->n6