From c568d79eef398b17435dc671a711e226ddcc2a71 Mon Sep 17 00:00:00 2001 From: Sanchime Date: Sun, 14 Aug 2022 17:04:45 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=BA=A2=E9=BB=91=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DataStructures/Trees/RedBlack.fs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/DataStructures/Trees/RedBlack.fs b/DataStructures/Trees/RedBlack.fs index 3946f30..1b41264 100644 --- a/DataStructures/Trees/RedBlack.fs +++ b/DataStructures/Trees/RedBlack.fs @@ -5,5 +5,24 @@ module RedBlack = type Color = Red | Black type RedBlackTree<'T> = - | Node of Color * 'T RedBlackTree * 'T * 'T RedBlackTree - | Leaf \ No newline at end of file + | Node of Color * Left: 'T RedBlackTree * Value: 'T * Right: 'T RedBlackTree + | Leaf + + let balance = function + | Black, Node (Red, Node (Red, a, x, b), y, c), z, d + | Black, Node (Red, a, x, Node (Red, b, y, c)), z, d + | Black, a, x, Node (Red, Node (Red, b, y, c), z, d) + | Black, a, x, Node (Red, b, y, Node (Red, c, z, d)) -> + Node (Red, Node (Black, a, x, b), y, Node (Black, c, z, d)) + | a, b, c, d -> Node (a, b, c, d) + + let insert x s = + let rec loop = function + | Leaf -> Node (Red, Leaf, x, Leaf) + | Node (color, a, y, b) as s -> + if x < y then balance (color, loop a, y, b) + elif y < x then balance (color, a, y, loop b) + else s + + loop s + \ No newline at end of file