From 9ba26195d2b9b4a7ba4b13372b0e881142c00e9f Mon Sep 17 00:00:00 2001 From: Drew Galbraith Date: Fri, 3 Nov 2023 21:59:57 -0700 Subject: [PATCH] [Glacier] Implement delete for binary tree. --- lib/glacier/container/binary_tree.h | 36 +++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/lib/glacier/container/binary_tree.h b/lib/glacier/container/binary_tree.h index 08bf80b..9c3998f 100644 --- a/lib/glacier/container/binary_tree.h +++ b/lib/glacier/container/binary_tree.h @@ -68,8 +68,40 @@ void BinaryTree::Insert(K key, V&& value) { template void BinaryTree::Delete(K key) { - // TODO: Implement Delete. - return; + auto node = FindOrInsertionParent(key); + if (node.empty() || node->key != key) { + return; + } + + RefPtr new_child = nullptr; + if (!node.left) { + // No children. + // Right child only. + new_child = node.right; + } else if (!node.right) { + // Left child only. + new_child = node.left; + } else { + // Find Successor. + auto successor = node.right; + while (successor.left) { + successor = successor.left; + } + new_child = successor; + if (successor != node.right) { + successor.parent.left = successor.right; + } + } + + if (node == root_) { + root_ = new_child; + } else { + if (node.parent.right == node) { + node.parent.right = new_child; + } else { + node.parent.left = new_child; + } + } } template