递归二进制搜索树插入

时间:2013-02-12 04:41:34

标签: java binary-search-tree

所以这是我的第一个java程序,但我已经完成了几年的c ++。我写了我认为应该有用的东西,但实际上并没有。所以我有一个规定,必须为这个电话写一个方法:

tree.insertNode(value);

其中value是int。 我想以递归的方式写它,原因很明显,所以我不得不做一个解决方法:

public void insertNode(int key) {
    Node temp = new Node(key);

    if(root == null) root = temp;

    else insertNode(temp);
}

public void insertNode(Node temp) {
    if(root == null)
        root = temp;

    else if(temp.getKey() <= root.getKey())
        insertNode(root.getLeft());

    else insertNode(root.getRight());
}

感谢您的任何建议。

5 个答案:

答案 0 :(得分:17)

// In java it is little trickier  as objects are passed by copy.
// PF my answer below.

// public calling method

public void insertNode(int key) {
    root = insertNode(root, new Node(key));
}

// private recursive call

private Node insertNode(Node currentParent, Node newNode) {

    if (currentParent == null) {
        return newNode;
    } else if (newNode.key > currentParent.key) {
        currentParent.right = insertNode(currentParent.right, newNode);
    } else if (newNode.key < currentParent.key) {
        currentParent.left = insertNode(currentParent.left, newNode);
    }

    return currentParent;
}

Sameer Sukumaran

答案 1 :(得分:3)

代码看起来与重载函数有点混淆。假设成员变量'left'和'right'分别是BSTree的左子项和右子项,您可以尝试以下列方式实现它:

 public void insert(Node node, int value) {
    if (value < node.value)
    {
        if (node.left != null)
        {
            insert(node.left, value);
        } 
        else
        {     
            node.left = new Node(value);
        }
    } 
    else if (value > node.value)
    {
        if (node.right != null)
        {
            insert(node.right, value);
        }
        else
        {
            node.right = new Node(value);
        }
    }
}

........
public static void main(String [] args)
{ 
     BSTree bt = new BSTree();
     Node root = new Node(100);
     bt.insert(root, 50);
     bt.insert(root, 150);
}

答案 2 :(得分:1)

你应该看看这篇文章。它有助于实现树结构和搜索,插入方法: http://quiz.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/

// This method mainly calls insertRec()
void insert(int key) {
   root = insertRec(root, key);
}

/* A recursive function to insert a new key in BST */
Node insertRec(Node root, int key) {

    /* If the tree is empty, return a new node */
    if (root == null) {
        root = new Node(key);
        return root;
    }

    /* Otherwise, recur down the tree */
    if (key < root.key)
        root.left = insertRec(root.left, key);
    else if (key > root.key)
        root.right = insertRec(root.right, key);

    /* return the (unchanged) node pointer */
    return root;
}

答案 3 :(得分:0)

您可以使用标准Integer(原始int的包装器)对象,而不是创建新的对象类型Node。最新支持java Integer / int 自动装箱。因此,您的方法insertNode(int key)也可以接受Integer参数(确保它不为空)。

编辑:请忽略上述评论。我不明白你真正的问题。您将不得不重载insertNode()。我想你是对的。

答案 4 :(得分:0)

但是insertNode?如果root不为null,那么当前的实现temp会丢失。

我想你想要像

这样的东西
root.getLeft().insertNode(temp);

root.getRight().insertNode(temp);

即。将新节点(temp)插入左子树或右子树。