Most efficient way to delete an entire binary search tree

I would like to know the most efficient way to delete an entire binary search tree. also prevent memory leaks, so you need to check if all nodes in subscreens are removed.

I can't think of any efficient way other than bypassing after the order, deleting as you go. any suggestions or ideas?

-2


source to share


2 answers


Just set the root node as null

. Let the garbage collector do its job.



+3


source


Removing all leaves from a binary tree in a thread discusses removing all children of a binary tree.

public static void deleteLeaves(BSTNode root) {  
  if (root == null)  
    return;  

  if (root.left != null && isLeaf(root.left))  
    root.left = null;  
  else  
    deleteLeaves(root.left);  

  if (root.right != null && isLeaf(root.right))  
    root.right = null;  
  else  
    deleteLeaves(root.right);  
}  

      



As the simplest, the root node will be installed on null

, and let the garbage collector do its job, which is O(1)

, not O(n)

in the above case.

+1


source







All Articles