Tuesday, August 11, 2015

Display Tree (Breadth First Search Output)

Step1: Write Tree class 

public class Tree {
 public int nodeValue;
 public Tree leftNode;
 public Tree rightNode;
}
Note: You can write get set functions, instead of declaring the tree members as public

Step 2: Write a sample test input & functions for it

public class TreeTestData {

 public static Tree createNode(int nodeVal, int left, Tree right)
 {
  Tree t = new Tree();
  t.nodeValue = nodeVal;
  t.leftNode = createNode(left, null, null);
  t.rightNode = right;
  return t;
 }
 
 public static Tree createNode(int nodeVal, int left, int right)
 {
  Tree t = new Tree();
  t.nodeValue = nodeVal;
  t.leftNode = createNode(left, null, null);
  t.rightNode = createNode(right, null, null);
  return t;
 }
 public static Tree createNode(int nodeVal, Tree left, Tree right)
 {
  Tree t = new Tree();
  t.nodeValue = nodeVal;
  t.leftNode = left;
  t.rightNode = right;
  return t;
 }
 
 public static Tree getSampleTree1()
 {
  Tree right = createNode(3, 2, 4);
  Tree currentLeftTree = createNode(1, 0, right);
  right = createNode(8,7,null);
  Tree currentRightTree = createNode(6, null, right);
  Tree t = createNode(5, currentLeftTree, currentRightTree);
  return t;
 }
}

Step 3: Construct an array of arrays using depth first search pre-order to store the nodes at each level. Go through the array using breadth first search and print the tree. If a node doesn't have a particular child, -1 is printed in this code.


import java.util.ArrayList;

public class TreeOperations {

 public void printNodeRecursively(Tree t, int level, 
              ArrayList<ArrayList<Integer>> levelNodes)
 {
  if(levelNodes.size() == level)
  {
   levelNodes.add(new ArrayList());
  }
  ArrayList nodes = levelNodes.get(level);
  if(t == null)
  {
   nodes.add(-1);
   return;
  }
  nodes.add(t.nodeValue);
  printNodeRecursively(t.leftNode, level+1, levelNodes);
  printNodeRecursively(t.rightNode, level+1, levelNodes);
 }

 public void printTree(Tree t)
 {
  final ArrayList<ArrayList<Integer>> levelNodes = new ArrayList<ArrayList<Integer>>();
  printNodeRecursively(t, 0, levelNodes);

  for(int level=0; level < levelNodes.size(); level++)
  {
   for(int nodeIndex = 0; nodeIndex < levelNodes.get(level).size(); nodeIndex++)
   {
    System.out.print(levelNodes.get(level).get(nodeIndex));
    System.out.print(" ");
   }
   System.out.println();
  }
 }

 public static void main(String[] args) {
  Tree t = TreeTestData.getSampleTree1();
  TreeOperations  treeOps = new TreeOperations();
  treeOps.printTree(t);
 }
}

No comments:

Post a Comment