I have written a BST using one class. Is my code okey or something could be better?
/**
* BST using one class
* @author Mateusz Stankiewicz
*/
public class Node {
private Comparable data;
private Node left;
private Node right;
private static Node root;
/**
* Tree constructor
*/
public Node() {
root = null;
}
/**
* Node constructor
*/
private Node(Comparable data) {
this.data = data;
left = null;
right = null;
}
/**
* Tree method to add new element
*
* @param data is a new data we want to add to a tree
*/
public void addToTree(int data) {
if (root == null)
root = new Node(data);
else
add(root, data);
}
// Private method that add new element
private void add(Node target, Comparable data) {
if (data.compareTo(target.data)<0) {
if (target.left == null)
target.left = new Node(data);
else
add(target.left, data);
} else {
if (target.right == null)
target.right = new Node(data);
else
add(target.right, data);
}
}
/**
* Prints out tree nodes
*/
public void printTree() {
print(root);
}
// Private recursive method to print a tree
private void print(Node n) {
if (n.left != null)
print(n.left);
System.out.println(n.data);
if (n.right != null)
print(n.right);
}
public static void main(String[] args) {
Node tree = new Node();
tree.addToTree(1);
tree.addToTree(7);
tree.addToTree(3);
tree.addToTree(4);
tree.addToTree(2);
tree.printTree();
}
}