我想递归地插入一个新节点,然后从函数insertRec返回新插入的节点。函数调用如下所示
void insert(int value) {
root = insertRec(root, null, value);
root = insertRec(root, null, 15);
root = insertRec(root, null, 6);
root = insertRec(root, null, 5);
root = insertRec(root, null, 3);
root = insertRec(root, null, 4);
//insertFixup(newNode);
}
RedBlackNode insertRec(RedBlackNode current, RedBlackNode prev, int value)
{
if(current == null) {
current = new RedBlackNode(value);
current.p = prev;
}
else if(current.key < value) {
current.right = insertRec(current.right, current, value);
}
else {
current.left = insertRec(current.left, current, value);
}
return current;
}如何在确保insertRec正确工作的同时做到这一点?现在,如果我不从current返回insertRec,那么我就无法正确地创建树。
发布于 2018-05-28 08:08:26
在您的代码中,您不处理节点的颜色,这也很重要吗?
通常,对于红黑树,插入是线性的,而不是递归的。类似于:
private void insert(int value) {
RedBlackNode parent = null;
RedBlackNode current = root;
while (current!=null){
parent = current;
if (value < current.key){
current = x.left;
//Here if you store the number of items on the left of a node increase it
}
else{
current = current.right;
//Here if you store the number of items on the right of a node increase it
}
}
RedblackNode newNode=new RedBlackNode(value);
newNode.p=parrent;
// Here if parent is null the new node is root of the tree
//if (parrent==null)
// root = newNode;
if (value < parent.key)
parent.left = newNode;
else
parent.right = newNode;
// Usually we add it as RED and then fix the tree to comply with red black tree rules
newNode.color=(RED);
fixTree(newNode);
}这是一些伪代码但这就是我的想法。在树上迭代,直到达到null为止。然后将新节点添加为红色,然后可能需要旋转树来修复颜色。
https://stackoverflow.com/questions/50561471
复制相似问题