如何使这个二叉搜索树工作??? (在 Java 中)
how to make this binary search tree work??? (in Java)
public void insert(int data) {
if (root == null) root = new AVLNode(data);
else {
AVLNode node = root;
while (node != null) {
if (node.data <= data) {
node = node.right;
}
else {
node = node.left;
}
}
node = new AVLNode(data);
}
}
我正在尝试创建一个二叉搜索树(非递归),然后访问 is 并进行前序遍历,但是当我打印 root 时,我只得到 1 个元素。我认为所有的插入都有效,但是根只有第一个插入并且它的左右没有引用任何东西,我认为这就是为什么我只得到 1 个元素。我如何将根引用到节点树的顶部?
这是节点 class btw
class AVLNode
{
AVLNode left, right;
int data;
/* Constructor */
public AVLNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public AVLNode(int n)
{
left = null;
right = null;
data = n;
}
}
问题出在变量的引用上。 While 循环直到达到 node
变量的空值,然后将新节点分配给它。但是在父 node.left
或 node.right
和新的 node
变量之间没有 link,因为它分配了 null
值。因此,您将值分配给一个未 linked 的变量,它将丢失。您需要将新节点直接分配给 node.left
或 node.right
,就像这个例子:
public void insert(int data) {
if (root == null) {
root = new AVLNode(data);
} else {
AVLNode node = root;
AVLNode newNode = new AVLNode(data);
while (node != null) {
if (node.data <= data) {
if (node.right == null) {
node.right = newNode;
node = null;
} else {
node = node.right;
}
} else {
if (node.left == null) {
node.left = newNode;
node = null;
} else {
node = node.left;
}
}
}
}
}
public void insert(int data) {
if (root == null) root = new AVLNode(data);
else {
AVLNode node = root;
while (node != null) {
if (node.data <= data) {
node = node.right;
}
else {
node = node.left;
}
}
node = new AVLNode(data);
}
}
我正在尝试创建一个二叉搜索树(非递归),然后访问 is 并进行前序遍历,但是当我打印 root 时,我只得到 1 个元素。我认为所有的插入都有效,但是根只有第一个插入并且它的左右没有引用任何东西,我认为这就是为什么我只得到 1 个元素。我如何将根引用到节点树的顶部? 这是节点 class btw
class AVLNode
{
AVLNode left, right;
int data;
/* Constructor */
public AVLNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public AVLNode(int n)
{
left = null;
right = null;
data = n;
}
}
问题出在变量的引用上。 While 循环直到达到 node
变量的空值,然后将新节点分配给它。但是在父 node.left
或 node.right
和新的 node
变量之间没有 link,因为它分配了 null
值。因此,您将值分配给一个未 linked 的变量,它将丢失。您需要将新节点直接分配给 node.left
或 node.right
,就像这个例子:
public void insert(int data) {
if (root == null) {
root = new AVLNode(data);
} else {
AVLNode node = root;
AVLNode newNode = new AVLNode(data);
while (node != null) {
if (node.data <= data) {
if (node.right == null) {
node.right = newNode;
node = null;
} else {
node = node.right;
}
} else {
if (node.left == null) {
node.left = newNode;
node = null;
} else {
node = node.left;
}
}
}
}
}