gpt4 book ai didi

java - RedBlackTree Mark Allen Weis 移除(x) 自顶向下方法

转载 作者:行者123 更新时间:2023-12-01 15:21:45 27 4
gpt4 key购买 nike

来自 Data Structures and Problem Solving Using Java 的原始 Mark Allen Weis RedBlackTree 实现找到here .

我似乎无法理解从树中删除节点的问题。读完wikipedia resource后我注意到“is_leaf()”函数..这个和 Mark Weis 实现的问题是没有办法分辨哪个节点是叶子,哪个不是叶子

void delete_one_child(struct node *n)
{
/*
* Precondition: n has at most one non-null child.
*/
struct node *child = is_leaf(n->right) ? n->left : n->right;

replace_node(n, child);
if (n->color == BLACK) {
if (child->color == RED)
child->color = BLACK;
else
delete_case1(child);
}
free(n);
}

Is_Leaf java实现

public boolean isLeaf(){
if(left == null && right == null){
return false;
}
return true;
}

控制台输出

value=1 color=1 leaf=true left=null right=14
value=2 color=1 leaf=true left=null right=5
value=5 color=0 leaf=true left=null right=null
value=7 color=0 leaf=true left=2 right=11
value=8 color=0 leaf=true left=null right=null
value=11 color=1 leaf=true left=8 right=null
value=14 color=1 leaf=true left=7 right=15
value=15 color=1 leaf=true left=null right=null

树格式(来自控制台)

└── (1) 1
└── (1) 14
├── (0) 7
│ ├── (1) 2
│ │ └── (0) 5
│ └── (1) 11
│ └── (0) 8
└── (1) 15

规则:

  1. 根是黑色的
  2. 每个红色节点都有一个黑色父节点
  3. 红色节点的所有子节点都是黑色的– 红色节点不能有红色子节点
  4. 从根到叶子的每条路径都包含相同的数字黑色节点数

所以我的问题是如何实现从 this 的删除红树和后树的实现?

最佳答案

我认为这是正确的 isLeaf() 代码:

public boolean isLeaf(RedBlackNode<AnyType> t ){
if(t.left.element == null && t.right.element == null){
return true;
}
return false;
}

关于java - RedBlackTree Mark Allen Weis 移除(x) 自顶向下方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10810111/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com