【问题标题】:Binary Tree Data Structure二叉树数据结构
【发布时间】:2015-11-17 00:00:00
【问题描述】:

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

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

【问题讨论】:

    标签: java tree binary-tree


    【解决方案1】:

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

    currentNode = newNode;

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

    我建议您使用 BinaryTree 类的构造函数而不是“初始化程序”方法。长度参数也不是必需的(string.length 做同样的事情)。

    终于可以将 Node 和 BinaryTree 统一到一个类中了。

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

    还有主类:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多