From a008409bcee1cc93dff4ab1e640ed4e229428538 Mon Sep 17 00:00:00 2001 From: Harald Wolff Date: Mon, 24 Feb 2020 17:25:51 +0100 Subject: [PATCH] Upgrade BTree<> --- btree/BTree.cs | 50 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/btree/BTree.cs b/btree/BTree.cs index 7c0ad60..619b2e5 100644 --- a/btree/BTree.cs +++ b/btree/BTree.cs @@ -1,10 +1,12 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Linq; +using ln.types.collections; namespace ln.types.btree { - public class BTree + public class BTree : IDict { public Comparison Comparison { get; } public int Count => count; @@ -229,6 +231,34 @@ namespace ln.types.btree } return null; } + private TreeNode FindFirstGE(K key) + { + TreeNode node = headNode; + TreeNode minNode = null; + + while (node != null) + { + if ((Comparison(node.Key, key) >= 0) && ((minNode == null) || (Comparison(node.Key, minNode.Key) < 0))) + minNode = node; + + int comp = Comparison(key, node.Key); + if (comp == 0) + return node; + else if (comp < 0) + { + if (node.Left == null) + return minNode; + node = node.Left; + } + else + { + if (node.Right == null) + return minNode; + node = node.Right; + } + } + return null; + } private TreeNode Previous(TreeNode node) { @@ -409,6 +439,21 @@ namespace ln.types.btree } } + public IEnumerable KeysGreaterEqual(K first) + { + TreeNode node = FindFirstGE(first); + while (node != null) + { + yield return node.Key; + node = Next(node); + } + } + + public void Add(object key, object value) => Add((K)key, (V)value); + public void Remove(object key) => Remove((K)key); + public bool ContainsKey(object key) => ContainsKey((K)key); + public object this[object key] { get => this[(K)key]; set => this[(K)key] = (V)value; } + public IEnumerable Keys { get @@ -434,6 +479,9 @@ namespace ln.types.btree } } + IEnumerable IDict.Keys => Keys; + IEnumerable IDict.Values => Values; + class TreeNode { public BTree Tree { get; }