简体   繁体   中英

Deleting all nodes and setting root to null in a binary search tree?

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-ac-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);
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM