【发布时间】:2019-12-25 00:50:28
【问题描述】:
有谁知道如何在 OCaml 中用类实现红黑树? 至少是类属性和初始化器?我是 OCaml 的新手。
我尝试了什么:
type data = {key: int; value: string}
class node (data: data) =
object (self)
val mutable d = data
val mutable color = 1
val mutable left = ref (None: node option)
val mutable right = ref (None: node option)
val mutable parent = ref (None: node option)
method getLeft = left
method getRight = right
method getParent = parent
method getColor = color
method getData = d
method setLeft (l: node option ref) = left := !l
method setRight (l: node option ref) = right := !l
method setParent (l: node option ref) = parent := !l
end;;
class rbtree =
object (self)
val mutable root = ref (None: node option)
val mutable nullNode = ref (None: node option)
method searchNode (aNode: node option ref) (key: data) = begin
if aNode = nullNode || key == (!aNode)#getData then aNode;
end;
end;;
我收到错误This expression has type node option
It has no method getData
我正在尝试用 C++ 编写类似这样的代码:
struct Node
{
int data;
Node *parent;
Node *left;
Node *right;
int color;
};
typedef Node *NodePtr;
class RedBlackTree
{
private:
NodePtr root;
NodePtr TNULL;
void initializeNULLNode(NodePtr node, NodePtr parent)
{
node->data = 0;
node->parent = parent;
node->left = nullptr;
node->right = nullptr;
node->color = 0;
}
NodePtr searchTreeHelper(NodePtr node, int key)
{
if (node == TNULL || key == node->data)
{
return node;
}
if (key < node->data)
{
return searchTreeHelper(node->left, key);
}
return searchTreeHelper(node->right, key);
}
};
【问题讨论】:
-
很难回答这个问题,因为没有明确的理由使用类来表示树类型。此外,您说“类”,就好像您希望拥有不止一个类。如果您更仔细地解释您的要求,这可能会有所帮助。但是,这听起来像是一项家庭作业,您应该准备好自己完成几乎所有的工作。特别是,您最好在编写一些代码并遇到特定问题后提出问题。
-
感谢您的回答。是的你是对的。这是家庭作业。我现在将使用我尝试过的代码更新我的问题。
-
@JeffreyScofield,你能再看看吗?谢谢。
-
关于错误
This expression has type node option. It has no method getData,看起来这是因为该值的类型为node options,但您正试图访问node类型的值的字段。所以你需要先把node从option中取出来。见stackoverflow.com/a/12288752/1187277 -
请阅读Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers? - 总结是这不是解决志愿者的理想方式,并且可能会适得其反。请不要将此添加到您的问题中。
标签: class oop ocaml binary-tree red-black-tree