This is a grade 12 assignment. One of the questions asks us to write a method in BTree class that takes either a BNode or an integer, and removes the node from the tree.
Here's what I've tried:
public void delete(BNode b){
if(b==null){
return;
}
if(b.getLeft()==null && b.getRight()==null){
b = null;
}
else{
//System.out.println("boiboi");
BNode tmp = b;
b = null;
add(tmp.getLeft());
add(tmp.getRight());
tmp = null;
}
}
public void delete(int v){
//System.out.println("gord");
delete(find(v));
}
Here's the add and find method which i think are correct:
public BNode find(int v){
return find(v, root);
}
public BNode find(int v, BNode branch){
if(branch == null || branch.getVal() == v){
return branch;
}
if(v<branch.getVal()){
return find(v, branch.getLeft());
}
else{//else if(v>branch.getVal())
return find(v, branch.getRight());
}
}
public void add(int v){
if(root == null){
root = new BNode(v);
}
else{
add(v, root);
}
}
public void add(int v, BNode branch){
if(v == branch.getVal()){
return;
}
if(v<branch.getVal()){
if(branch.getLeft() == null){
branch.setLeft(new BNode(v));
}
else{
add(v, branch.getLeft());
}
}
else{
if(branch.getRight() == null){
branch.setRight(new BNode(v));
}
else{
add(v, branch.getRight());
}
}
}
public void add(BNode n){
if(n==null){
return;
}
add(n.getVal());
}
Here's my testing class:
BTree bTree = new BTree();
bTree.add(50);
bTree.add(60);
bTree.add(40);
bTree.add(35);
bTree.add(55);
bTree.add(45);
bTree.add(51);
bTree.delete(60);
bTree.display();
the output is still everything i've added: 35 40 45 50 51 55 60 even if i tried to delete 51 which is the simplest case, still same output. Any help or suggestions would be appreciated, thank you.