inserting in binary tree doesn't work using java

流过昼夜 提交于 2021-02-17 03:03:50

问题


I'm currently learning about trees using java and i have some errors going on here in the insertion of items in a binary tree I don't why it doesn't work

this is the code: tree node:

public class TNode {
    int data;
    TNode left;
    TNode right;

    public TNode(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}

tree class:

public class Tree {
    TNode root;

    public Tree(){
        root = null;
    }

    public TNode insertNode(TNode item, int d) {
        if (item == null) {
            return new TNode(d);
        }

         if (d < item.data) {
            item.left = insertNode(item, d);
        }

        if (d > item.data) {
            item.right = insertNode(item, d);
        } else {
            return item;
        }

        return item;
    }

    public void add(int d) {
        insertNode(root, d);
    }
}

Whenever I add an item the root remains null with no right or left items if someone can help I'll be really thankful


回答1:


root is always null because you never assign value to it.

you can add to the beginning of your method check and assign it

public TNode insertNode(TNode item, int d){
    if(item == null){
        TNode node = new TNode(d);
        if (root == null) { 
            root = node;
        }
        return node
    }
    ... rest of method isn't changed...

Also when you are recursing you should make a call with a proper child node instead of always calling with item, so for example first case would be:

    item.left = insertNode(item.left, d);

For second case you would just use item.right instead.




回答2:


Fine code, but recursing does not step further

item.left = insertNode(item.left, d);
item.right = insertNode(item.right, d);

And the initial root is not updated:

root = insertNode(root, d);

The else part or final return is superfluous.


Something on the code style

insertNode has a node as input, and returns the updated node value, hence the call "pattern" should look like

X = insertNode(X, d); // X is some expression

This is because java can never assign to the passed argument expression: it has no pass-by-reference, but pass-by-value; f(x) never assigns to x.



来源:https://stackoverflow.com/questions/50193957/inserting-in-binary-tree-doesnt-work-using-java

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