How to write findMinimum of a lazy deleted Binary Search Tree in Java

旧巷老猫 提交于 2020-05-16 04:06:29

问题


I am writing a class for a Binary Search Tree in Java that uses lazy deletion (instead of removing the node from the tree, it sets a "deleted" flag to true)

My question is, how would I implement a findMin function for a tree like this? The normal method of just going to the leftmost leaf wouldn't work because that lead may be "deleted".

For example, A tree like this where you delete 20, 5, and 17

         25
     *20     30
   *17        89
  *5

should return 25 when you call findMin().

My implementation looks like this:

public int findMin() {
    return doFindMin(root);
}

private int doFindMin(TreeNode node) {
    if (node == null) {
        return -1;
    } else if (node.getLeftChild() != null) {
        return doFindMin(node.getLeftChild());
    } else if (!node.isDeleted()) {
        return node.getKey();
    } else if (node.getRightChild() != null){
        return doFindMin(node.getRightChild());
    } else return -1;
}

When I call the function with the situation described above, it returns -1. If I don't delete 17, it correctly returns 17 as the minimum.

Any help with this would be greatly appreciated. Thanks.

EDIT: 17 was placed incorrectly in the tree, original post has been updated to fix this problem.


回答1:


Do an inorder recording nodes that aren't marked as deleted. The first non-deleted element is the minimum.You could break out of traversal once you found the first one. You could do something like below:

void inOrderForMinimum( TreeNode node, int[] min ) {
    if ( node != null && min[0] == -1 ) {
       inOrderForMinimum( node.getLeftChild(), min );
       if ( !node.isDeleted() ) {
          min[0] = node.value;
       }
       inOrderForMinimum( node.getRightChild(), min );
   }
}

Call this like :

private int findMinimum( TreeNode root ) {
   int[] min = new int[]{-1};
   inOrderForMinimum( root, min );
   return min[0];
}


来源:https://stackoverflow.com/questions/48895238/how-to-write-findminimum-of-a-lazy-deleted-binary-search-tree-in-java

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