Implement Heap using a Binary Tree

后端 未结 7 1665
栀梦
栀梦 2020-12-14 03:49

This question has been asked before in Stack Exchange but it went unanswered.

Link to the previously asked question: Binary Heap Implemented via a Binary Tree Struct

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 04:03

    HEAP IMPLEMENTATION USING TREE

    I am answering my own question that takes O(log n), but the limitation is to keep a pointer to the parent. if we don't keep a pointer to the parent, we need approximately O(n). I posted this question to get a solution for O(log n)

    Here are the steps to calculate next unoccupied leaf (we have a pointer to the parent node):

    x = last inserted node. We save this after every insertion.
    y = tmp node
    z = next unoccupied node (next insertion)
       if x is left child
          z = x -> parent -> rightchild (problem solved.. that was easy)
       else if x is right child
          go to x's parent, until parent becomes left child. Let this node be y
          (subtree rooted at y's sibling will contain the next unoccupied node)
          z = y -> parent -> right -> go left until null
    

    This is O(log n), but needs a pointer to the parent.

    O(n) solution would be pretty easy, just level order the tree and we get the location of the next unoccupied node.

    My question is: how to locate next unoccupied node in O(log n) without using a parent pointer.

    Thanks.

提交回复
热议问题