DFS (InOrder, PreOrder, PostOrder)
-----------------------------------------------------------------------------------------------------------
Recursive solution:
InOrder:
left -> middle -> right
Wrong Code:
public void printInOrder(){
if(left!=null){
left.printInOrder();
System.out.print("-" + data + "-");
right.printInOrder();
}
else{
if(right!=null){
System.out.print("-" + data + "-");
right.printInOrder();
}
else{
System.out.print("-" + data + "-");
}
}
}
Right Code:
public void printInOrder(){
if(left!=null)
left.printInOrder();
System.out.print("-" + data + "-");
if(right!=null)
right.printInOrder();
}
PreOrder:
middle->left->right
public void printPreOrder(){
System.out.print("-"+ data + "-");
if(left!=null)
left.printPreOrder();
if(right!=null)
right.printPreOrder();
}
PostOrder:
left->right->middle
public void printPostOrder(){
if(left!=null)
left.printPostOrder();
if(right!=null)
right.printPostOrder();
System.out.print("-" + data + "-");
}
Non_recursive solution: (use Stack)
public void printDF(){
if(this.empty()){System.out.println("Empty tree.");}
Stack<BNode> sk = new Stack<BNode>();
sk.push(root);
while(!sk.empty()){
BNode n = sk.pop();
System.out.print("-"+ n.data + "-");
if(n.right!=null)
sk.push(n.right);
if(n.left!=null)
sk.push(n.left);
}
System.out.println("");
}
BFS:
Non-recursive solution: (use Queue)
public void printBF(){
if(this.empty()){System.out.println("Empty Tree.");}
Queue<BNode> q = new LinkedList<BNode>();
q.add(root);
while(!q.isEmpty()){
BNode n = q.remove();
System.out.print("-" + n.data + "-");
if(n.left!=null)
q.add(n.left);
if(n.right!=null)
q.add(n.right);
}
System.out.println("");
}