Implement Heap using a Binary Tree

后端 未结 7 1649
栀梦
栀梦 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:15

    Assuming you want to use a linked binary tree, with no pointers to parent nodes, then the only solution I can think of is keeping a counter of number of children in each node.

    availableLeaf(node) {
        if( node.left is Empty || node.right is Empty )
            return node ;
        else
           if( node.left.count < node.right.count )
               return availableLeaf(node.left)
           else
               return availableLeaf(node.right)
    }
    

    This strategy also balances the number of nodes on each side of each subtree, which is beneficial (though extremely slightly).

    This is O(log n). Keeping track of count on insertion requires to come all the way up to the roof, but this doesn't change the O(lon n) nature of this operation. Similar thing with deletion.

    Other operations are the usual, and preserve their performance characteristics.

    Do you need the details or prefer to work them out by yourself?

    If you want to use a linked binary tree, with no other information than left and right pointers, then I'd suggest you to initiate a bounty for at least 100,000 points. I'm not saying it's impossible (because I don't have the math to prove it), but I'm saying that this has not been found in several decades (which I do know).

提交回复
热议问题