Why is the root always null in this method insert method for binary tree

岁酱吖の 提交于 2019-12-02 09:25:43

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 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.

Java is pass-by value language. In case of objects you pass the value of the reference, thus, creating new reference.

public void insertNode(Node r, Node n) {
    if(r == null) {
        r = n;
    }

Here you substitute the new reference to the root with the other reference; original reference to root (t.root) left unchanged.

To fix this issue you can get rid of the first parameter in the insertNode() method - the tree's root is the part of its implementation, so the tree already knows the reference to its root. Change all rs inside insertNode() to this.root.

When you set r within the method, it does not affect the node that you pass in. So t.root is never set.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!