Java中的简单二进制搜索树

时间:2014-01-28 21:57:13

标签: java data-structures

这里有一个Java简单BST的代码,密钥只有int,但是当我想测试它并使用print()时,可以打印root.key root.rightroot.leftnull

public class BST {

    private class Node {
        private int key;
        private Node left, right;

        public Node(int key) {
            this.key = key;
        }
    }

    private Node root;

    public BST(int key) {
        root = new Node(key);
    }

    public void insert(int key) {
        insert(root, key);
    }

    private void insert(Node x, int key) {
        if (x == null) {
            x = new Node(key);
        }
        if (key > x.key) {
            insert(x.right, key);
        } else if (key < x.key) {
            insert(x.left, key);
        } else {
            x.key = key;
        }
    }

    public void print() {
        print(root);
    }

    private void print(Node x) {
        System.out.print(x.key + " ");
        if (x.left != null)
            print(x.left);
        if (x.right != null)
            print(x.right);
    }
}

例如,当我插入25,9,10,30,40并调用print()时,它只会打印25。

1 个答案:

答案 0 :(得分:5)

x = new Node(key);

这项任务基本上抛弃了new Node,因为x只是一个局部变量。你在这里修改调用者引用,你只是修改调用者给你的引用的本地副本。您可以做的是return x并让调用者分配它:

x = insert(x, 3);

insert看起来像这样:

private Node insert(Node x, int key) {
    if (x==null){
        return new Node(key);
    }
    if (key > x.key) {
        x.right = insert(x.right, key);
    }else if (key < x.key) {
        x.left = insert(x.left, key);
    }else{
        x.key = key;
    }
    return x;
}