korayucar
6/11/2016 - 5:57 PM

a method for in order binary search tree traversal in O(1) memory iteratively. no stack needed.

a method for in order binary search tree traversal in O(1) memory iteratively. no stack needed.

public class MorrisTraversal{


static class Node{

  int data;
  Node left;
  Node right;
  Node (int data)
  {
    this.data = data;
    left = null;
    right = null;
  }

}


static class BinaryTree{

static Node root;
void MorrisTraversal (Node node){

  if(node == null)
    return;
  Node current , pre;
  current = node;
  while(current != null)
  {
    if(current.left == null)
    {
      System.out.print(current.data + " ");
      current = current.right;
    }
    else{
      pre = current.left;
      while(pre.right != null && pre.right != current ){
        pre = pre.right;
      }
      if(pre.right == null){
        pre.right = current;
        current = current.left;
      }
      else{
        pre.right = null;
        System.out.print(current.data+"  ");
        current = current.right;
      }
    }
  }

}

}


public static void main(String args[]) {
       int sum = 14;
       BinaryTree tree = new BinaryTree();
       tree.root = new Node(4);
       tree.root.left = new Node(3);
       tree.root.right = new Node(4);
       tree.root.left.left = new Node(1);
       tree.root.left.right = new Node(3);

       tree.MorrisTraversal(tree.root);
   }


}