/** * Returns the node with a given key and fills the path variable with the corresponding * information * * @param key Key to search for * @param path Path variable to fill * @return The node with a given key */ protected TreeNode<K, V> findNode(K key, Path<TreeNode<K, V>> path) { path.addRightStep(null); TreeNode<K, V> node = this.root; while (node != null) { int comparisonResult = node.getKey().compareTo(key); if (comparisonResult < 0) { if (path != null) path.addRightStep(node); node = node.getRightNode(); } else if (comparisonResult > 0) { if (path != null) path.addLeftStep(node); node = node.getLeftNode(); } else { return node; } } return null; }
/** * Deletes a node with the specified key, if one is found, and stores the path traveled path in * path * * @param key Key to remove * @param path Traveled path * @return The deleted node's value, if no node was found returns null */ protected V delete(K key, Path<TreeNode<K, V>> path) { TreeNode<K, V> node = this.findNode(key, path); if (node == null) { return null; } V result = node.getValue(); if (node.getLeftNode() == null) { this.joinTrees(node.getRightNode(), path.getLastParent(), path.getLastSide()); } else if (node.getRightNode() == null) { this.joinTrees(node.getLeftNode(), path.getLastParent(), path.getLastSide()); } else { path.addRightStep(node); TreeNode<K, V> minNode = this.getLeafBySide(node.getRightNode(), Side.LEFT, path); node.setKey(minNode.getKey()); node.setValue(minNode.getValue()); this.joinTrees(minNode.getRightNode(), path.getLastParent(), path.getLastSide()); } super.size--; return result; }