数组中二叉树的存储元素

时间:2019-07-15 21:34:06

标签: arrays algorithm recursion binary-tree

我想将我的二叉树中的元素存储到数组中,但不知道如何执行... 我已经有一个用于数组大小的count方法,现在我需要将int元素存储到数组中

public int countNode() {
    if (this.root == null) {
        return 0;
    } else {
        int count = 1;
        count += root.l.countNode();
        count += root.r.countNode();
        return count;
    }
}

public int[] arrayStorage() {
    int[] a = new int[countNode()];


}

1 个答案:

答案 0 :(得分:0)

您可以使用队列通过遍历树的级别顺序将其添加到数组中。

对于二叉树,我们不采用这种方法的主要原因是,当二叉树没有像堆一样完成时,这浪费了数组中的大量空间。