二叉树的递归插入

1 java tree recursion binary-tree reference

我正在研究用于插入二叉搜索树的代码.它适用于我插入的第一个节点,使其成为根,但之后它似乎没有插入任何节点.我确定设置左/右引用是个问题,但我无法弄明白.请帮忙!

    //params: key of node to be inserted, parent node
    public void insert(int newKey, TreeNode parent){

    //if the root of the tree is empty, insert at root
    if(this.getRoot() == null){
        this.root = new TreeNode(newKey, null, null);
    }

    //if the node is null, insert at this node
    else if(parent == null)
        parent = new TreeNode(newKey, null, null);


    else{
        //if the value is less than the value of the current node, call insert on the node's left child
        if(newKey < parent.getKey()) {
                insert(newKey, parent.getLeft());
        }
        //greater than value of current node, call insert on node's right child
        else if(newKey > parent.getKey()){
                insert(newKey, parent.getRight());
        }
        //same as value of current node, increment iteration field by one
        else if(newKey == parent.getKey())
            parent.incrementIterations();
    }

}
Run Code Online (Sandbox Code Playgroud)

我的treenodes有键,左,右和迭代字段,以及getter/setter函数.先感谢您!

use*_*871 5

public Node insertNode(Node head, int data) {

        if(head == null){
            head = new Node();
            head.data = data;
            return head;
        }
        if(head.data < data) {
            head.right = insertNode(head.right,data);
        } else {
            head.left = insertNode(head.left, data);
        }
        return head;
    }
Run Code Online (Sandbox Code Playgroud)