inserting in binary tree doesn't work using java

前端 未结 2 404
梦毁少年i
梦毁少年i 2021-01-27 03:43

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

相关标签:
2条回答
  • 2021-01-27 04:30

    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.

    0 讨论(0)
  • 2021-01-27 04:36

    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.

    0 讨论(0)
提交回复
热议问题