in my code I have created a TreeNode class where each node has a int N field which is the number of subtrees, this is the code for the deletion of a TreeNode in a randomized BTS tree
void remove(int id)
{
if(isID(id)) {
removeR(head,id);
}else
{
System.out.println("There's no warehouse with that ID!");
}
}
private TreeNode removeR(TreeNode h,int id)
{
if (h==null) return null;
int TreeNodeID=h.getId();
if(id<TreeNodeID)
removeR(h.l,id);
if(id>TreeNodeID)
removeR(h.r,id);
if(id==TreeNodeID)
h=joinLR(h.l,h.r);
return h;
}
private TreeNode joinLR(TreeNode a,TreeNode b)
{
int NA=a.N+b.N;
if(a==null)
return b;
if(b==null)
return a;
if(Math.random()*NA<1.0*a.N)
{
a.r=joinLR(a.r,b);
return a;
} else
{
b.l=joinLR(a,b.l);
return b;
}
}
If I insert for example a TreeNode with an ID of 1 and select to remove this Node, the code will do : remove(id)->removeR(head,id)->h=joinLR(h.l,h.r), my problem is that in the joinLR function this piece of code
int NA=a.N+b.N;
will make the next two ifs dead code
if(a==null)
return b;
if(b==null)
return a;
I did a lot of examples , if I use a or b the code will be unusable , the only solution is to write it after the two ifs , but then the code doesn't work properly , does anyone has any idea?