In this lesson we have learnt about the tree traverse and binary search tree, two new method in searching for precise data points.
Tree Traverse:
Preorder traverse
Inorder traverse
Postorder traverse
Binary Search Tree Class
The following class includes adding, removing, searching, getting and setting method for a BSTNode object.
import java.util.*;
public class BSTNode {
private int value;
private BSTNode left;
private BSTNode right;
public BSTNode(int value)
{
this.value = value;
left = null;
right = null;
}
public boolean add(int value) {
if (value == this.value)
return false;
else if (value <this.value) {
if (left == null) {
left = new BSTNode(value);
return true;
} else
return left.add(value);
} else if (value > this.value) {
if (right == null) {
right = new BSTNode(value);
return true;
} else
return right.add(value);
}
return false;
}
public boolean search(int value) {
if (value == this.value)
return true;
else if (value < this.value) {
if (left == null)
return false;
else
return left.search(value);
} else if (value > this.value) {
if (right == null)
return false;
else
return right.search(value);
}
return false;
}
public boolean remove(int value, BSTNode parent) {
if (value < this.value) {
if (left != null)
return left.remove(value, this);
else
return false;
} else if (value > this.value) {
if (right != null)
return right.remove(value, this);
else
return false;
} else {
if (left != null && right != null) {
this.value = right.minValue();
right.remove(this.value, this);
} else if (parent.left == this) {
parent.left = (left != null) ? left : right;
} else if (parent.right == this) {
parent.right = (left != null) ? left : right;
}
return true;
}
}
public int minValue() {
if (left == null)
return value;
else
return left.minValue();
}
public int getValue(){
return this.value;
}
public BSTNode setLeftChild(BSTNode root){
left = root;
return left;
}
public BSTNode getLeft(){
return left;
}
}
Binary Search Tree Class
In this class, the methods are specific applied for different use in Binary Search Tree.
import java.util.*;
public class BinarySearchTree {
private BSTNode root;
public BinarySearchTree()
{
root = null;
}
public boolean add(int value){
if(root == null){
root = new BSTNode(value);
return true;
}
else{
return root.add(value);
}
}
public boolean search(int value) {
if (root == null)
return false;
else
return root.search(value);
}
public boolean remove(int value) {
if (root == null)
return false;
else {
if (root.getValue() == value) {
BSTNode auxRoot = new BSTNode(0);
auxRoot.setLeftChild(root);
boolean result = root.remove(value, auxRoot);
root = auxRoot.getLeft();
return result;
} else {
return root.remove(value, null);
}
}
}
}