Traversing an imbalanced binary tree in array form

孤人 提交于 2019-12-07 22:28:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!