Programming Assignment 6 Implement a BST class that keeps a pointer to the TNode
ID: 3572818 • Letter: P
Question
Programming Assignment 6 Implement a BST class that keeps a pointer to the TNode that is the root of the BST. Implement two constructors, a no parameters constructor and a copy constructor. Also implement an insert method that inserts new data into the tree. Programming Assignment 6 Implement a BST class that keeps a pointer to the TNode that is the root of the BST. Implement two constructors, a no parameters constructor and a copy constructor. Also implement an insert method that inserts new data into the tree. Programming Assignment 6 Implement a BST class that keeps a pointer to the TNode that is the root of the BST. Implement two constructors, a no parameters constructor and a copy constructor. Also implement an insert method that inserts new data into the tree.Explanation / Answer
class BinaryTreenode {
private Comparable key;
private Object data;
private BinaryTreenode left, right;
public BinaryTreenode(){}
public BinaryTreenode(Comparable k, Object d,
BinaryTreenode l, BinaryTreenode r) {
key = k;
data = d;
left = l;
right = r;
}
public Object getData() {
return data;
}
public void setData(Object ob) { data = ob; }
public Comparable getKey() {return key;}
public BinaryTreenode getLeft() {return left;}
public BinaryTreenode getRight() {return right;}
public void setKey(Comparable k) {key = k;}
public void setLeft(BinaryTreenode l) {left = l;}
public void setRight(BinaryTreenode r) {right = r;}
}
class BST {
private BinaryTreenode root;
public BST() { root = null; }
public BST(BinaryTreenode bt){
this.bt=bt;
}
public void insert(Comparable key, Object data) throws DuplicateException {
if (root == null) {
root = new BinaryTreenode(k, null, null);
}
else insert(root, k);
}
private static void insert(BinaryTreenode T, Comparable k) throws DuplicateException {
if (T.getKey().equals(k)) throw new DuplicateException();
if (k.compareTo(T.getKey()) < 0) {
if (T.getLeft() == null) T.setLeft( new BinaryTreenode(k, null, null) );
else insert(T.getLeft(), k);
}
else {
if (T.getRight() == null) T.setRight( new BinaryTreenode(k, null, null) );
else insert(T.getRight(), k);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.