为什么在此方法的二叉树插入方法中,根总是为空 [英] Why is the root always null in this method insert method for binary tree
问题描述
我正在尝试为BST类实现递归插入节点方法
Iam trying to implement a recursive insert node method for BST class
public void insertNode(Node r, Node n)
{
if(r == null)
{
System.out.println("r=n"+ n.data);
r = n;
}
else
{
System.out.println("r=! null finding place in tree for "+ n.data);
if(n.data <= r.data)
{
if(r.left == null)
r.left = n;
else
insertNode(r.left, n);
}
else
{
if(r.right == null)
r.right = n;
else
insertNode(r.right, n);
}
}
}
我试图像这样调用此方法:
Im trying to invoke this method like so:
int[] arrTree = {34, 2, 56, 12, 44, 39, 56, 1};
BT t = new BT();
for (int i = 0; i < arrTree.length; i++)
{
//System.out.println("Tree Root = "+ t.getRoot());
BT.Node n = t.new Node(arrTree[i]);
t.insertNode(t.root, n);
}
但是我总是得到以下输出:
But Im always getting this output:
r=n34
r=n2
r=n56
r=n12
r=n44
r=n39
r=n56
r=n1
Node是BT的内部类.
Node is an inner class of BT.
经过数小时的运行和尝试不同的操作后,我无法弄清楚我做错了什么.
I cannot figure it out after hours of running and trying different things what Im doing wrong.
推荐答案
从显示的代码来看,我的钱在这里出错了:
Judging by the code you've shown, my money's on the error being here:
public void insertNode(Node r, Node n)
{
if(r == null)
{
System.out.println("r=n"+ n.data);
r = n; //you overwrite the value of r but never use it
}
Node r
实际上是对t.root
所引用内容的单独引用,因此将r
替换为另一个值不会改变t.root
所引用方法之外的内容.您可以在方法内部修改引用的数据,但不能修改引用本身.
Node r
is actually a separate reference to whatever t.root
refers to, so replacing r
with another value won't change whatever t.root
refers to outside the method. You can modify the referenced data inside a method, but not the reference itself.
这篇关于为什么在此方法的二叉树插入方法中,根总是为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!