[31, 35, 40, 10, 42]represented as the complete binary tree
As we have observed, this is not yet a heap. But consider applying the demote method repeatedly, working backwards, beginning with parent as the last node in the tree. For the last three nodes, i.e. those holding 42, 10 and 40, there is nothing to do, since a leaf node, where both left and right subtrees are empty, is already a heap. The last non-leaf node holds 35. Applying demote, with this node as parent, leads to the tree
![]()
where we have had to exchange the 35 and the 42. Now apply the demote method, with parent as the next node working backwards, which is the root node holding 31. The result is
![]()
where the 31 has had to sink two layers to the bottom. There are now no more nodes and we are finished.
![]()
It is no accident that the resulting tree is properly heap ordered. We have observed that demote, when called for parent, restores heap order below parent, provided both left and right sub-trees of parent are already heap ordered. But if we work backwards from the end of the tree, in opposite level order, applying demote repeatedly, every time we call demote, both left and right subtrees will already be properly heap ordered. Calling it finally, for the root node, completes the heapification of the whole tree.