Tuesday, August 11, 2015

Tree Depth First Searches


public class Tree {
 public int nodeValue;
 public Tree leftNode;
 public Tree rightNode; 
}

public class TreeOperations {

 public void preorderSearch(Tree t)
 {
  if(t == null) return;
  System.out.print(t.nodeValue + " ");
  preorderSearch(t.leftNode);
  preorderSearch(t.rightNode);
 }
 
 public void inorderSearch(Tree t)
 {
  if(t == null) return;
  inorderSearch(t.leftNode);
  System.out.print(t.nodeValue + " ");
  inorderSearch(t.rightNode);
 }
 
 public void postorderSearch(Tree t)
 {
  if(t==null) return;
  postorderSearch(t.leftNode);
  postorderSearch(t.rightNode);
  System.out.print(t.nodeValue + " " );
 }

 public static void main(String[] args) {

  Tree t = TreeTestData.getSampleTree1();
  TreeOperations  treeOps = new TreeOperations();
  treeOps.preorderSearch(t);
  treeOps.inorderSearch(t);
  treeOps.postorderSearch(t);
 }

}

Note: For the TreeTestData Class look at post Tree part 1 step 2.

No comments:

Post a Comment