Question

I am new to Java. I was practicing a few programming questions when I came across a question to delete all the nodes in a BST.

I wanted to implement the below program in Java: http://www.geeksforgeeks.org/write-a-c-program-to-delete-a-tree/

I wrote the following code, but it only deletes the leftmost and the rightmost element in a BST. Please help

public boolean isLeaf(Node n){
    return (n.lchild==null && n.rchild==null);

}
public void deleteTree(){
    deleteTree(root);
}
public void deleteTree(Node n){
    if(n==null)
        return;
    if(n.lchild!=null && isLeaf(n.lchild))
        n.lchild=null;
    else
        deleteTree(n.lchild);
    if(n.rchild!=null && isLeaf(n.rchild))
        n.rchild=null;
    else
        deleteTree(n.rchild);
}
Was it helpful?

Solution

The tutorial you are following are about the language C which differs greatly from Java. In C you have to allocate and free memory manually (by the malloc and free methods in the link you listed). However, Java manages all that behind the scenes. You could say that Java's version of malloc is new. But for freeing the memory Java has a garbage collector that free up memory by deleting unreferenced objects. To 'delete' your tree in Java all you have to do is de-reference your root like so:

public void deleteTree() {
    root = null;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top