数组中二叉树中的存储元素



我想将二叉树中的元素存储到数组中,但不知道如何做......我已经有一个数组大小的 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()];

}

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

我们不对二叉树

采用这种方法的主要原因是,当二叉树不像堆那样不完整时,这会浪费数组中的大量空间。

最新更新