java - 二叉树的递归插入

标签 java recursion reference tree binary-tree

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

    //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();
    }

}

我的树节点有键、左、右和迭代字段,以及 getter/setter 函数。 先感谢您!

最佳答案

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;
    }

关于java - 二叉树的递归插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26270200/

相关文章:

c++ - 如何理解 "Pass By Reference Within a Function"w3schools示例?

Java:从非静态比较器对其外部类字段的引用

java - 硬币找零的空间优化解决方案

java - 使用 Java 添加 Soap Action header

java - 带有点(.)字符的ibatis java.util.Map参数

algorithm - 大 O 符号和递归

java - 安装Elasticsearch 5.5 启动服务失败

c++ - 函数结束后子节点的树递归c++缺失值

javascript - 避免树行走递归的最佳方法

javascript - 为什么 react.js 不能识别自己的 node.js 模块?