Search code examples
data-structuresbinary-treeheapmax-heap

Determine whether a binary tree is max heap


I am writing a function to determine whether a given binary tree is a max heap. If the binary tree had only one node (the root), would it be considered a valid max heap?


Solution

  • To be considered a valid max-heap, a binary tree must satisfy two properties:

    1. Shape property. The tree must be a complete binary tree. That is, every level except the last must be full. If the last is not full, it is left-filled.
    2. Heap property. Every child node must be less than or equal to its parent.

    A tree with a single node satisfies both properties, so it is a valid max-heap.