Tree
In this section, we will implement naive binary tree.
We first define root and internal tree with has left and right connection.
class SSETree{
private SSETreeInternal root;
private class SSETreeInternal {
int val;
private SSETreeInternal left;
private SSETreeInternal right;
public SSETreeInternal(int val) {
this.val = val;
left = null;
right = null;
}
}
public SSETree(int val){
SSETreeInternal sseTreeInternal = new SSETreeInternal(val);
root = sseTreeInternal;
}
}
Then we define add function which take O(log(n)) because it is stored on either left or right. it is better if it is a &quout;complete binary tree&quout; because some time it can be unbalanced.
public void add(int val){
add(root, val);
}
private SSETreeInternal add (SSETreeInternal root, int val){
if (root == null){
return new SSETreeInternal(val);
}else {
if (val > root.val){
root.right = add(root.right, val);
}else{
root.left = add(root.left, val);
}
return root;
}
}
Then we define print function which take O(n) because it iterates through all element.
public void print(){
print(root);
}
private void print(SSETreeInternal root){
if (root != null) {
print(root.left);
System.out.print(root.val + " ");
print(root.right);
}
}
Tree is useful because it takes O(log(n)) time to do things and it is also sorted.
You can try to run the code here:
Run on jdoodle