From 7fd978449e87c9fec02e789598032d596f3587b2 Mon Sep 17 00:00:00 2001 From: Vincenzo Palazzo Date: Sun, 3 Apr 2022 17:50:04 +0200 Subject: [PATCH] datatypes: draft interface RB-Tree Signed-off-by: Vincenzo Palazzo --- vlib/datatypes/rbtree.v | 86 ++++++++++++++++++++++++++++++++++++ vlib/datatypes/rbtree_test.v | 6 +++ 2 files changed, 92 insertions(+) create mode 100644 vlib/datatypes/rbtree.v create mode 100644 vlib/datatypes/rbtree_test.v diff --git a/vlib/datatypes/rbtree.v b/vlib/datatypes/rbtree.v new file mode 100644 index 0000000000..2dfc3cdc6a --- /dev/null +++ b/vlib/datatypes/rbtree.v @@ -0,0 +1,86 @@ +module datatypes + +/// Internal rapresentation of the tree node +[heap] +struct RBTreeNode { +mut: + is_init bool // mark node as initialized + value T // value of the node + parent &RBTreeNode = 0 + left &RBTreeNode = 0 + right &RBTreeNode = 0 + color bool // mark the node as red or black +} + +// new_root_node create new root rbt node +fn new_rbt_root_node(value &T) &RBTreeNode { + return &RBTreeNode{ + is_init: true + value: value + color: false + parent: new_rbt_none_node(true) + left: new_rbt_none_node(true) + right: new_rbt_none_node(true) + } +} + +// new_node create a new rb node with a parante +fn new_rbt_node(parent &RBTreeNode, value &T) &RBTreeNode { + return &RBTreeNode{ + is_init: true + value: value + parent: parant + } +} + +// new_none_node create a dummy node. +fn new_rbt_none_node(init bool) &RBTreeNode { + return &RBTreeNode{ + is_init: init + } +} + +// set_to_red set the color of the node to red +fn (mut node RBTreeNode) set_to_red() { + node.color = true +} + +// set_to_black set the color of the node to black +fn (mut node RBTreeNode) set_to_black() { + node.color = false +} + +// Pure Red-Black Tree implementation +// +// Pure V implementation of the RB-Tree +// Time complexity on main operation O(N log N) +// in the wrost case still O(N log N) +// Space complexity O(N) +pub struct RBTree { +mut: + root &RBTreeNode = 0 +} + +pub fn (mut rbt RBTree) insert(value &T) bool { + return false +} + +pub fn (mut rbt RBTree) contains(value &T) bool { + return false +} + +pub fn (mut rbt RBTree) remove(value &T) bool { + return false +} + +pub fn (rbt &RBTree) is_empty() bool { + return rbt.root == 0 +} + +pub fn (rbt &RBTree) max() ?&T { + return error('not implemented') +} + +pub fn (rbt &RBTree) min() ?&T { + return error('not implemented') +} diff --git a/vlib/datatypes/rbtree_test.v b/vlib/datatypes/rbtree_test.v new file mode 100644 index 0000000000..9eee8abded --- /dev/null +++ b/vlib/datatypes/rbtree_test.v @@ -0,0 +1,6 @@ +module datatypes + +fn test_init_rbtree() { + rbtree := RBTree{} + assert rbtree.is_empty() +}