If I store a binary tree in an array, how do I avoid the wasted space?

后端 未结 1 529
别跟我提以往
别跟我提以往 2021-02-06 17:17

Often we need trees in algorithms and I get out a tree with lots of pointers and recursion.
Sometimes I need more speed an I put the tree into an 2D array like so:



        
相关标签:
1条回答
  • 2021-02-06 17:27

    A binary tree can be stored in an array more efficiently as explained here: http://en.wikipedia.org/wiki/Binary_tree#Arrays:

    From Wikipedia:

    In this compact arrangement, if a node has an index i, its children are found at indices (2i + 1) (for the left child) and (2i + 2) (for the right), while its parent (if any) is found at index floor((i-1)/2) (assuming the root has index zero).

    This method benefits from more compact storage and better locality of reference, particularly during a preorder traversal. However, it is expensive to grow and wastes space proportional to (2H - n) for a tree of height H with n nodes.

    In other words, it will waste space if your tree is not a complete binary tree, but it will still be a bit more compact than a plain 2D array.

    0 讨论(0)
提交回复
热议问题