How to properly clear an entire binary tree in Java?

I have a simple binary search tree class with an instance variable of type Node, which is the root. It's nothing complicated, just the same BST base class that you saw earlier, with a Node class with a field for a data type and two links to the left and right nodes. I want a method that cleans a tree. Initially, I thought well, here it is:

void clearTree() { root = null; }

but my professor claims that this really does not clear the tree from memory, since there are still links to nodes from the parent nodes in the tree ... Although we do not have links to them. Is he right to say that? If so, why does this not clear the tree from memory? I thought that as soon as we lose the link to it, it will be garbage collection.

+4
source share
3 answers

Your professor is right in the sense that a root of zero will not free the whole tree. In languages ​​like C, if you make the root=nullwhole tree still in memory.

But in Java, as @radai said, the garbage collector will clear it for you if you no longer have references to tree nodes. So, in the context of Java, make root=nullwill work.

In any case, if you need to clear every node of the tree (which, for example, is necessary in C / C ++), you can use the pos-order algorithm. Of course, you will need to adapt the algorithm to your variable names and structures (or classes if you want to apply them in Java).

void clearTree(treenode *node) {
    if (node != NULL) {
        clearTree( node->leftChild );
        clearTree( node->rightChild );
        delete( node ); // Or in Java, node = null;
    }
}
+3
source

everything that you can no longer achieve (through any link / pointer in your code) is entitled to garbage collection.

, - - , node, GC , .

, eclipse, ( hprof, jdk, 20 , ), , Node

+3

, . A:

class A {
   private B b;
   private C c;

   public A(B b, C c){
     this.b = b;
     this.c = c;
   }

}

:

A a = new A(new B(), new C());

:

a = null;

, A, , - ( ). , .

And I think this is the same with the tree. It will recursively claim that another object is not available. IF there are no other references to this root.

EDIT:

Gif shows how the GC decides whether an object is accessible: here

0
source

Source: https://habr.com/ru/post/1530746/


All Articles