most efficient way to delete an entire binary search tree

北慕城南 提交于 2019-12-14 03:27:05

问题


I would like to know the most efficient way to delete an entire binary search tree. also not to let any memory leak so having to check if all the nodes in the sub trees are deleted first.

I cant think of any efficient way besides post order traversal, deleting as you go. any suggestions or ideas?


回答1:


Just set your root node as null. Let the garbage collector to do its job.




回答2:


Deleting all leaves from a binary tree thread discusses about deleting all children of 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);  
}  

How ever simplest will be set root node to null and let garbage collector do its job which will be O(1) rather than O(n) in above case..



来源:https://stackoverflow.com/questions/12853118/most-efficient-way-to-delete-an-entire-binary-search-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!