在Java中实现二叉树数据结构

时间:2018-07-09 23:31:22

标签: java tree binary

我正在尝试在Java中实现二叉树数据结构。这是我的代码。我对java还是很陌生,不太了解我的错误在哪里。谢谢。我收到以下错误消息:binTree.java:21:错误:预期使用类,接口或枚举

class Node {
int value;
Node left;
Node right;

Node(int value) {
    this.value = value;
    right = null;
    left = null;
}
}

public class BinTree {

Node root;

}
private Node addRecursive(Node current, int value) {
if (current == null) {
    return new Node(value);
}

if (value < current.value) {
    current.left = addRecursive(current.left, value);
} else if (value > current.value) {
    current.right = addRecursive(current.right, value);
} else {
    // value already exists
    return current;
}

return current;
}
public void add(int value) {
root = addRecursive(root, value);
}
System.out.println();
    System.out.println("testcase 1:");
    BinTree binTree2 = new BinTree();
    binTree2.insertNode(new Node(3));
    binTree2.insertNode(new Node(201));
    binTree2.insertNode(new Node(60));
    binTree2.insertNode(new Node(30));
    binTree2.insertNode(new Node(45));
    binTree2.treeWalk();

2 个答案:

答案 0 :(得分:0)

您在节点根字段之后的第21行使用了右括号,您不应该在 另外,您将需要一种主要方法或Junit tedt案例来启动测试(在底部,从System.out.println()之前开始)

答案 1 :(得分:0)

您的方法需要放置在BinTree类中,并且您要执行的代码需要包装在这样的主函数中

public class BinTree {

    Node root;


    private Node addRecursive(Node current, int value) {
        if (current == null) {
            return new Node(value);
        }

        if (value < current.value) {
            current.left = addRecursive(current.left, value);
        } else if (value > current.value) {
            current.right = addRecursive(current.right, value);
        } else {
        // value already exists
            return current;
        }

        return current;
    }

    public void add(int value) {
        root = addRecursive(root, value);
    }

    public static void main(String []args){
        System.out.println();
        System.out.println("testcase 1:");
        BinTree binTree2 = new BinTree();
        binTree2.insertNode(new Node(3));
        binTree2.insertNode(new Node(201));
        binTree2.insertNode(new Node(60));
        binTree2.insertNode(new Node(30));
        binTree2.insertNode(new Node(45));
        binTree2.treeWalk();
    }

}

您似乎缺少了诸如insertNode和treeWalk之类的方法,但是在实现这些方法后应该可以对其进行编译。