Wednesday, December 9, 2015

Preorder Traversal of a Binary Search Tree using Stack in java

import java.util.ArrayList;

public class BST_Impl {
BST_Node root = null;

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 10, 4, 0, 34, 23, -2, -2, 5, 12, 9, 15};
BST_Impl tree = new BST_Impl();
for (int i = 0; i < arr.length; i++) {
tree.insert(new BST_Node(arr[i]));

}



System.out.println("preorder using stack:");
tree.preorder_ByStack(tree.root);

}

public void preorder_ByStack(BST_Node root) {
Stack_BST_IMPL stack = new Stack_BST_IMPL();
ArrayList list = new ArrayList();
if (root != null) {
stack.push(new Stack_Node(root));
}
while (!stack.isEmpty()) {
Stack_Node node = stack.pop();
list.add(node.value.value);
if (node.value.right != null) {
stack.push(new Stack_Node(node.value.right));
}

if (node.value.left != null) {
stack.push(new Stack_Node(node.value.left));
}

}

System.out.println(list);
}



public void insert(BST_Node node) {
BST_Node temp = root;
if (root == null) {
root = node;
} else {
while (temp != null) { // inserting as leave of a node
if (temp.value > node.value) {
if (temp.left == null) {
temp.left = node;
break;
}
temp = temp.left;
} else if (temp.value < node.value) {
if (temp.right == null) {
temp.right = node;
break;
}
temp = temp.right;
} else {
System.out.println("cannot enter equal number:"
+ temp.value);
break;
}
}

}

}

}

class BST_Node {
BST_Node left;
BST_Node right;
int value;

public BST_Node(int value) {
this.value = value;
}

}

class Stack_Node {
BST_Node value;
Stack_Node next;

public Stack_Node(BST_Node value) {
this.value = value;
}

}

class Stack_BST_IMPL {
int size = 0;
Stack_Node top = null;

void push(Stack_Node node) {
if (top == null) {
top = node;
size = 1;
} else {
node.next = top;
top = node;
size++;
}

}

public Stack_Node pop() {
Stack_Node temp;
temp = top;
top = top.next;
temp.next = null;
size--;
return temp;

}

public boolean isEmpty() {
if (size == 0) {
return true;
}

return false;
}

}

No comments:

Post a Comment