java - 我不明白如何移动树的一部分
问题描述
我的目标是创建一个 BST:当我插入一个节点时,我将它插入根,如果要插入的元素已经存在,则将现有元素移动到根。如果删除一个节点,则将该节点的父节点移动到根节点。
class BSTNode {
BSTNode left = null;
BSTNode rigth = null;
int data = 0;
public BSTNode() {
super();
}
public BSTNode(int data) {
this.left = null;
this.rigth = null;
this.data = data;
}
@Override
public String toString() {
return "BSTNode [left=" + left + ", rigth=" + rigth + ", data=" + data + "]";
}
}
class BinarySearchTree {
BSTNode root = null;
public BinarySearchTree() {
}
public void insert(int data) {
BSTNode node = new BSTNode(data);
if (root == null) {
root = node;
return;
}else{
BSTNode currentNode = root;
BSTNode parentNode = null;
if (currentNode.data == data)
return;
if (currentNode.data > data) {
parentNode = node;
BSTNode existing = searchNode(data);
if (existing != null){
parentNode = existing;
parentNode.rigth = currentNode;
}else{
parentNode.rigth = currentNode;
}
} else {
parentNode = node;
BSTNode existing = searchNode(data);
if (existing != null){
parentNode = existing;
parentNode.left = currentNode;
}else{
parentNode.left = currentNode;
}
}
root = parentNode;
}
}
public BSTNode searchNode(int data) {
if (empty())
return null;
return searchNode(data, root);
}
public BSTNode searchNode(int data, BSTNode node) {
if ((node.left != null && node.left.data == data) || (node.rigth != null && node.rigth.data == data)) {
if (node.left.data == data){
BSTNode existing = node.left;
node.left = null;
return existing;
}
if(node.rigth.data == data){
BSTNode existing = node.rigth;
node.rigth = null;
return existing;
}
else if (node.data > data)
return searchNode(data, node.left);
else if (node.data < data)
return searchNode(data, node.rigth);
}
return null;
}
我还没有处理删除。我被困在插入功能上。
我的想法是:用新根替换旧根,如果它更小,则将旧根挂在新根的左侧,或者如果它更大,则挂在右侧。另外,如果是旧根小于新根,则在旧根的右分支上寻找新根的第一个最大元素,并将其作为新根的右分支钩住来移动。如果它更大,则相反。
但我没有能力。谁能帮我?也许在关闭“问题”之前,我还需要一些关于删除操作的建议。
解决方案
推荐阅读
- wordpress - 如何在 Wordpress 上将我的图像 src 标签从绝对 url 更改为相对 url?
- android - 删除/更新笔记后 RecyclerView 不更新
- javascript - 从中获取事件后获取 iframe 的实例
- python - docker build 产生损坏的 pythin 库安装
- spring - 订购多个 RouterFunction
- database - BCP 带有逗号分隔符的文件
- python - 如何在python中搜索选择和编辑文本文件的特定部分
- sql - 使用oracle sql的当年出生日期
- performance-testing - Gatling 活跃用户降至零以延长运行时间
- c# - 无法将日期转换为特定格式