java - 二叉搜索树不会添加新节点?
问题描述
我正在尝试编写一种递归方法来将节点添加到二叉搜索树(不允许重复)。由于某种原因,该方法仅在树为空时有效,否则它会打印出“重复”(即使它不是重复的)。我是编程新手,希望能得到解决此问题的帮助和提示。谢谢你。
//add new node to the tree
public void add(int data) {
Node<Integer> newNode = new Node<>(data); //create new node with the data
//if the tree is empty, the newNode becomes the root
if (size() == 0) {
root = newNode;
return;
}
//otherwise, check if node should be placed to right or left
add(data, root);
}
private void add(int data, Node<Integer> node) {
//base case - found an empty position
if (node == null) {
node = new Node<Integer>(data);
}
if (data < node.data) {
add(data, node.left);
}
else if (data > node.data) {
add(data, node.right);
}
else if (data == node.data) {
System.out.println("Duplicate. This value cannot be added to the tree.");
}
}
解决方案
当您的树为空时,节点会正确添加到其中。第一个add(int data)
功能很好。
第二个add(int data, Node<Integer> node)
功能存在问题。如果树已经有一个元素,则调用此方法。如果传递的节点大于或小于传递的值,则使用当前节点的左子或右子再次调用该函数。这个值可能(最终会)为空。这导致在您的方法的基本情况下创建一个节点,从而满足此data == node.data
条件,因为该节点确实是使用数据值创建的。因此,您会收到错误消息。
为了解决这个问题,第二个功能可以改变如下:
private void add(int data, Node<Integer> node) {
if (data < node.data) {
if (node.left != null) {
add(data, node.left);
} else {
node.left = new Node<>(data);
}
}
else if (data > node.data) {
if (node.right != null) {
add(data, node.right);
} else {
node.right = new Node<>(data);
}
add(data, node.right);
}
else if (data == node.data) {
System.out.println("Duplicate. This value cannot be added to the tree.");
}
}
看到基本案例已被移除。如果遇到基本情况,我们不会为我们提供对任何树节点的引用。因此添加data
到树是不可能的(节点参数绝不能为空)。
此外,如果子项为空,代码将添加data
为子项。node
这保证了该方法不会递归地使用 nullnode
参数,并且data
更重要的是添加到其应有的位置。
推荐阅读
- codeigniter - 如何在codeigniter的form_input中设置日期时间格式
- angular - [WDS] 断线怎么解决!Angular 7 和 Ionic 4 中的错误
- python - Peewee:在模型实例化时动态设置 table_name
- python-3.x - 在 mac 上找不到 Virtualenv 命令
- java - Sl4j 不记录来自 JPA 的 sql 语句
- python-3.x - 检查无限级数是否可以单独被一个数字整除?
- node.js - 像 Youtube 一样的视频流,在 Node js 中播放的主要视频之间有广告视频
- android - 如何在项目中找到墙纸 URL?
- asp.net - Global.asax Application_Error IIS7WorkerRequest.RaiseCommunicationError.ExplicitFlush()
- java - 如何用新字符替换字符串中的第 n 个字符?