二叉树数据结构

Binary Tree Data Structure

我目前正在为我的数据结构解决这个二叉树(不是二叉搜索树)问题 class。但是,当我尝试从根打印树时,调试显示即使我初始化了树

根它仍然为空
public class Node {

    int integerValue = 0;
    public Node leftNode = null;
    public Node rightNode = null;

    public Node (int inputInt){
        this.integerValue = inputInt;
    }
}

在知道不会有删除或添加的树中插入数组元素

public class BinaryTree {
    public void initializeTree(int[]string, int length, int currentPosition, Node currentNode){
        if(currentPosition < length){
            Node newNode = new Node(string[currentPosition]);
            currentNode = newNode;
            initializeTree(string,length, 2*currentPosition +1, currentNode.leftNode);
            initializeTree(string,length, 2*currentPosition +2, currentNode.rightNode);
        }
    }

    public void printTree(Node root){
        if(root != null){
            System.out.print(root.integerValue + " ");
            printTree(root.leftNode);
            printTree(root.rightNode);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        int [] array = {0,1,2};
        ArrayTree tree = new ArrayTree();
        BinaryTree bTree = new BinaryTree();
        Node root = null;
        Node currentNode = root;

        bTree.initializeTree(array, 3, 0, currentNode);
        bTree.printTree(root);
    }
}

当您将 currentNode 参数传递给初始化程序时,您传递的是对象的 引用(指针),在本例中为 null。在方法中重新分配变量时:

currentNode = newNode;

现在 currentNode 引用了一个新的 Node 实例,但是 Main class 上的 currentNode 变量没有更新,因此它将保持为空。

我建议您使用 BinaryTree class 的构造函数而不是 "initializer" 方法。长度参数也不是必需的(string.length 做同样的事情)。

您终于可以将节点和二叉树合二为一了class。

public class BinaryTree {
    Integer integerValue;
    BinaryTree left, right;

    public BinaryTree(int[] string, int currentPosition) {
        if (currentPosition < string.length){
            this.integerValue = string[currentPosition];
            this.left = new BinaryTree(string, 2 * currentPosition + 1);
            this.right = new BinaryTree(string, 2 * currentPosition + 2);
        }
    }

    public void printTree() {
        if (this.integerValue != null){
            System.out.print(this.integerValue + " ");
            this.left.printTree();
            this.right.printTree();
        }
    }
}

和主要 class:

public class Main {
    public static void main(String[] args) {
        int [] array = {0, 1, 2};
        BinaryTree root = new BinaryTree(array, 0);
        root.printTree();
    }
}