问题
An imbalanced (or non-heap) binary tree can be represented using an array as follows:
array = [1, 2, null, 3, 4, 5, 6, null, 7, 8, null]
1
/ \
2 null
/ \
3 4
/ \ / \
5 6 null 7
/ \
8 null
How can I do a tree traversal using the given array? More specifically, how can I calculate a parent's left and right children's indices?
In a balanced tree (such as a heap tree), we can easily calculate two children indices using their parent's index, and vice versa, as follows.
leftChildIdx = 2 * parentIdx + 1
rightChildIdx = 2 * parentIdx + 2
Is there an easy way to traverse this imbalanced, or seemingly random, binary tree, using the array?
来源:https://stackoverflow.com/questions/58596754/traversing-an-imbalanced-binary-tree-in-array-form