Check if a given Binary Tree is a Heap

Last Updated : 24 Oct, 2026

Given the root of a binary tree, determine whether the tree satisfies the heap property.

Binary tree needs to fulfill the following two conditions for being a heap:

  • It should be a complete tree (i.e. Every level of the tree, except possibly the last, is completely filled, and all nodes are as far left as possible.).
  • Every node’s value should be greater than or equal to its child node (considering max-heap).

Examples:

Input: 

Check-if-a-given-Binary-Tree-is-a-Heap-

Output: true
Explanation : The binary tree is a complete binary tree, and every node’s value is greater than or equal to its children’s values. Therefore, all heap properties are satisfied, and the tree is a valid max-heap.

Input: 

Check-if-a-given-Binary-Tree-is-a-Heap-2

Output: false
Explanation: Max heap property fails as child node with value 4 is greater than parent node with value 3.

Try It Yourself
redirect icon

Two Separate Recursive Checks - O(n) Time and O(h) Space

The idea is to recursively check the following.

  • To check if tree is complete, we assign an index to each node and check if left is at 2i + 1 and right at 2i + 2
  • To check greater, we recursively compare values of left and right children with the current

Detailed Steps

  • Count the total number of nodes in the binary tree.
  • Recursively check whether the tree is complete by assigning an index to each node.
  • For a node at index i, its left and right children are assigned indices 2i + 1 and 2i + 2.
  • If any node gets an index greater than or equal to the total number of nodes, the tree is not complete.
  • Recursively check the max-heap property: every parent must be greater than or equal to its children.
  • If both the completeness and max-heap conditions hold, return true; otherwise, return false.
C++
#include <iostream>
using namespace std;

class Node
{
public:
    int data;
    Node* left;
    Node* right;

    Node(int x)
    {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Count total number of nodes
int countNodes(Node* root)
{
    if (root == nullptr)
        return 0;

    return 1 + countNodes(root->left) + countNodes(root->right);
}

// Check if the tree is complete
bool isComplete(Node* root, int index, int totalNodes)
{
    if (root == nullptr)
        return true;

    // If index is beyond total nodes, tree is not complete
    if (index >= totalNodes)
        return false;

    return isComplete(root->left, 2 * index + 1, totalNodes) &&
           isComplete(root->right, 2 * index + 2, totalNodes);
}

// Check max-heap property
bool isMaxHeap(Node* root)
{
    if (root == nullptr)
        return true;

    if (root->left != nullptr && root->data < root->left->data)
        return false;

    if (root->right != nullptr && root->data < root->right->data)
        return false;

    return isMaxHeap(root->left) &&
           isMaxHeap(root->right);
}

bool isHeap(Node* root)
{
    int totalNodes = countNodes(root);

    return isComplete(root, 0, totalNodes) &&
           isMaxHeap(root);
}

int main()
{
    Node* root = new Node(97);
    root->left = new Node(46);
    root->right = new Node(37);
    root->left->left = new Node(12);
    root->left->right = new Node(3);
    root->right->left = new Node(7);
    root->right->right = new Node(31);

    cout << (isHeap(root) ? "true" : "false");

    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

struct Node
{
    int data;
    struct Node* left;
    struct Node* right;
};

struct Node* newNode(int x)
{
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));

    node->data = x;
    node->left = NULL;
    node->right = NULL;

    return node;
}

// Count total number of nodes
int countNodes(struct Node* root)
{
    if (root == NULL)
        return 0;

    return 1 + countNodes(root->left) + countNodes(root->right);
}

// Check if the tree is complete
bool isComplete(struct Node* root, int index, int totalNodes)
{
    if (root == NULL)
        return true;

    // If index is beyond total nodes, tree is not complete
    if (index >= totalNodes)
        return false;

    return isComplete(root->left, 2 * index + 1, totalNodes) &&
           isComplete(root->right, 2 * index + 2, totalNodes);
}

// Check max-heap property
bool isMaxHeap(struct Node* root)
{
    if (root == NULL)
        return true;

    if (root->left != NULL && root->data < root->left->data)
        return false;

    if (root->right != NULL && root->data < root->right->data)
        return false;

    return isMaxHeap(root->left) &&
           isMaxHeap(root->right);
}

bool isHeap(struct Node* root)
{
    int totalNodes = countNodes(root);

    return isComplete(root, 0, totalNodes) &&
           isMaxHeap(root);
}

int main()
{
    struct Node* root = newNode(97);
    root->left = newNode(46);
    root->right = newNode(37);
    root->left->left = newNode(12);
    root->left->right = newNode(3);
    root->right->left = newNode(7);
    root->right->right = newNode(31);

    printf("%s", isHeap(root) ? "true" : "false");

    return 0;
}
Java
class Node {
    int data;
    Node left;
    Node right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Count total number of nodes
    static int countNodes(Node root) {
        if (root == null)
            return 0;

        return 1 + countNodes(root.left) + countNodes(root.right);
    }

    // Check if the tree is complete
    static boolean isComplete(Node root, int index, int totalNodes) {
        if (root == null)
            return true;

        // If index is beyond total nodes, tree is not complete
        if (index >= totalNodes)
            return false;

        return isComplete(root.left, 2 * index + 1, totalNodes) &&
               isComplete(root.right, 2 * index + 2, totalNodes);
    }

    // Check max-heap property
    static boolean isMaxHeap(Node root) {
        if (root == null)
            return true;

        if (root.left != null && root.data < root.left.data)
            return false;

        if (root.right != null && root.data < root.right.data)
            return false;

        return isMaxHeap(root.left) &&
               isMaxHeap(root.right);
    }

    static boolean isHeap(Node root) {
        int totalNodes = countNodes(root);

        return isComplete(root, 0, totalNodes) &&
               isMaxHeap(root);
    }

    public static void main(String[] args) {
        Node root = new Node(97);
        root.left = new Node(46);
        root.right = new Node(37);
        root.left.left = new Node(12);
        root.left.right = new Node(3);
        root.right.left = new Node(7);
        root.right.right = new Node(31);

        System.out.println(isHeap(root) ? "true" : "false");
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


# Count total number of nodes
def countNodes(root):
    if root is None:
        return 0

    return 1 + countNodes(root.left) + countNodes(root.right)


# Check if the tree is complete
def isComplete(root, index, totalNodes):
    if root is None:
        return True

    # If index is beyond total nodes, tree is not complete
    if index >= totalNodes:
        return False

    return (isComplete(root.left, 2 * index + 1, totalNodes) and
            isComplete(root.right, 2 * index + 2, totalNodes))


# Check max-heap property
def isMaxHeap(root):
    if root is None:
        return True

    if root.left is not None and root.data < root.left.data:
        return False

    if root.right is not None and root.data < root.right.data:
        return False

    return isMaxHeap(root.left) and isMaxHeap(root.right)


def isHeap(root):
    totalNodes = countNodes(root)

    return isComplete(root, 0, totalNodes) and isMaxHeap(root)


if __name__ == "__main__":
    root = Node(97)
    root.left = Node(46)
    root.right = Node(37)
    root.left.left = Node(12)
    root.left.right = Node(3)
    root.right.left = Node(7)
    root.right.right = Node(31)

    print("true" if isHeap(root) else "false")
C#
using System;

class Node
{
    public int data;
    public Node left;
    public Node right;

    public Node(int x)
    {
        data = x;
        left = null;
        right = null;
    }
}

class GfG
{
    // Count total number of nodes
    static int countNodes(Node root)
    {
        if (root == null)
            return 0;

        return 1 + countNodes(root.left) + countNodes(root.right);
    }

    // Check if the tree is complete
    static bool isComplete(Node root, int index, int totalNodes)
    {
        if (root == null)
            return true;

        // If index is beyond total nodes, tree is not complete
        if (index >= totalNodes)
            return false;

        return isComplete(root.left, 2 * index + 1, totalNodes) &&
               isComplete(root.right, 2 * index + 2, totalNodes);
    }

    // Check max-heap property
    static bool isMaxHeap(Node root)
    {
        if (root == null)
            return true;

        if (root.left != null && root.data < root.left.data)
            return false;

        if (root.right != null && root.data < root.right.data)
            return false;

        return isMaxHeap(root.left) &&
               isMaxHeap(root.right);
    }

    static bool isHeap(Node root)
    {
        int totalNodes = countNodes(root);

        return isComplete(root, 0, totalNodes) &&
               isMaxHeap(root);
    }

    static void Main()
    {
        Node root = new Node(97);
        root.left = new Node(46);
        root.right = new Node(37);
        root.left.left = new Node(12);
        root.left.right = new Node(3);
        root.right.left = new Node(7);
        root.right.right = new Node(31);

        Console.WriteLine(isHeap(root) ? "true" : "false");
    }
}
JavaScript
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Count total number of nodes
function countNodes(root) {
    if (root === null)
        return 0;

    return 1 + countNodes(root.left) + countNodes(root.right);
}

// Check if the tree is complete
function isComplete(root, index, totalNodes) {
    if (root === null)
        return true;

    // If index is beyond total nodes, tree is not complete
    if (index >= totalNodes)
        return false;

    return isComplete(root.left, 2 * index + 1, totalNodes) &&
           isComplete(root.right, 2 * index + 2, totalNodes);
}

// Check max-heap property
function isMaxHeap(root) {
    if (root === null)
        return true;

    if (root.left !== null && root.data < root.left.data)
        return false;

    if (root.right !== null && root.data < root.right.data)
        return false;

    return isMaxHeap(root.left) &&
           isMaxHeap(root.right);
}

function isHeap(root) {
    const totalNodes = countNodes(root);

    return isComplete(root, 0, totalNodes) &&
           isMaxHeap(root);
}

// Driver code
const root = new Node(97);
root.left = new Node(46);
root.right = new Node(37);
root.left.left = new Node(12);
root.left.right = new Node(3);
root.right.left = new Node(7);
root.right.right = new Node(31);

console.log(isHeap(root) ? "true" : "false");

Output
true

Single Recursion - O(n) Time and O(h) Space

We check the max-heap property and completeness together during a single recursive traversal. For each node, verify its position and compare its value with its children.

Step by Step Approach:

  • Start from the root with an index representing its position in the complete binary tree.
  • For each node, check whether its index is within the total number of nodes. If not, the tree is not complete.
  • Check that the node is greater than or equal to its left and right children.
  • Recursively apply the same checks to the left and right subtrees.
  • Leaf nodes automatically satisfy the heap property because they have no children.
  • If every node passes both checks, the tree is a valid max-heap.
C++
#include <iostream>
using namespace std;

class Node
{
public:
    int data;
    Node* left;
    Node* right;

    Node(int x)
    {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Count total number of nodes
int countNodes(Node* root)
{
    if (root == nullptr)
        return 0;

    return 1 + countNodes(root->left) +
           countNodes(root->right);
}

// Check completeness and max-heap property
bool checkHeap(Node* root, int index, int totalNodes)
{
    if (root == nullptr)
        return true;

    // Check if the tree is complete
    if (index >= totalNodes)
        return false;

    // Check max-heap property
    if (root->left != nullptr &&
        root->data < root->left->data)
        return false;

    if (root->right != nullptr &&
        root->data < root->right->data)
        return false;

    return checkHeap(root->left, 2 * index + 1, totalNodes) &&
           checkHeap(root->right, 2 * index + 2, totalNodes);
}

bool isHeap(Node* root)
{
    int totalNodes = countNodes(root);

    return checkHeap(root, 0, totalNodes);
}

int main()
{
    Node* root = new Node(97);
    root->left = new Node(46);
    root->right = new Node(37);
    root->left->left = new Node(12);
    root->left->right = new Node(3);
    root->right->left = new Node(7);
    root->right->right = new Node(31);

    cout << (isHeap(root) ? "true" : "false");

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct Node
{
    int data;
    struct Node* left;
    struct Node* right;
};

struct Node* newNode(int x)
{
    struct Node* node = malloc(sizeof(struct Node));

    node->data = x;
    node->left = NULL;
    node->right = NULL;

    return node;
}

// Count total number of nodes
int countNodes(struct Node* root)
{
    if (root == NULL)
        return 0;

    return 1 + countNodes(root->left) +
           countNodes(root->right);
}

// Check completeness and max-heap property
bool checkHeap(struct Node* root, int index, int totalNodes)
{
    if (root == NULL)
        return true;

    // Check if the tree is complete
    if (index >= totalNodes)
        return false;

    // Check max-heap property
    if (root->left != NULL &&
        root->data < root->left->data)
        return false;

    if (root->right != NULL &&
        root->data < root->right->data)
        return false;

    return checkHeap(root->left, 2 * index + 1, totalNodes) &&
           checkHeap(root->right, 2 * index + 2, totalNodes);
}

bool isHeap(struct Node* root)
{
    int totalNodes = countNodes(root);

    return checkHeap(root, 0, totalNodes);
}

int main()
{
    struct Node* root = newNode(97);
    root->left = newNode(46);
    root->right = newNode(37);
    root->left->left = newNode(12);
    root->left->right = newNode(3);
    root->right->left = newNode(7);
    root->right->right = newNode(31);

    printf("%s", isHeap(root) ? "true" : "false");

    return 0;
}
Java
class Node {
    int data;
    Node left;
    Node right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Count total number of nodes
    static int countNodes(Node root) {
        if (root == null)
            return 0;

        return 1 + countNodes(root.left) + countNodes(root.right);
    }

    // Check completeness and max-heap property
    static boolean checkHeap(Node root, int index, int totalNodes) {
        if (root == null)
            return true;

        // Check if the tree is complete
        if (index >= totalNodes)
            return false;

        // Check max-heap property
        if (root.left != null && root.data < root.left.data)
            return false;

        if (root.right != null && root.data < root.right.data)
            return false;

        return checkHeap(root.left, 2 * index + 1, totalNodes)
            && checkHeap(root.right, 2 * index + 2, totalNodes);
    }

    static boolean isHeap(Node root) {
        int totalNodes = countNodes(root);

        return checkHeap(root, 0, totalNodes);
    }

    public static void main(String[] args) {

        Node root = new Node(97);
        root.left = new Node(46);
        root.right = new Node(37);
        root.left.left = new Node(12);
        root.left.right = new Node(3);
        root.right.left = new Node(7);
        root.right.right = new Node(31);

        System.out.println(isHeap(root));
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


# Count total number of nodes
def countNodes(root):
    if root is None:
        return 0

    return 1 + countNodes(root.left) + countNodes(root.right)


# Check completeness and max-heap property
def checkHeap(root, index, totalNodes):
    if root is None:
        return True

    # Check if the tree is complete
    if index >= totalNodes:
        return False

    # Check max-heap property
    if root.left is not None and root.data < root.left.data:
        return False

    if root.right is not None and root.data < root.right.data:
        return False

    return (checkHeap(root.left, 2 * index + 1, totalNodes) and
            checkHeap(root.right, 2 * index + 2, totalNodes))


def isHeap(root):
    totalNodes = countNodes(root)

    return checkHeap(root, 0, totalNodes)


# Driver code
root = Node(97)
root.left = Node(46)
root.right = Node(37)
root.left.left = Node(12)
root.left.right = Node(3)
root.right.left = Node(7)
root.right.right = Node(31)

print("true" if isHeap(root) else "false")
C#
using System;

class Node
{
    public int data;
    public Node left;
    public Node right;

    public Node(int x)
    {
        data = x;
        left = null;
        right = null;
    }
}

class GfG
{
    // Count total number of nodes
    static int countNodes(Node root)
    {
        if (root == null)
            return 0;

        return 1 + countNodes(root.left) +
               countNodes(root.right);
    }

    // Check completeness and max-heap property
    static bool checkHeap(Node root, int index, int totalNodes)
    {
        if (root == null)
            return true;

        // Check if the tree is complete
        if (index >= totalNodes)
            return false;

        // Check max-heap property
        if (root.left != null &&
            root.data < root.left.data)
            return false;

        if (root.right != null &&
            root.data < root.right.data)
            return false;

        return checkHeap(root.left, 2 * index + 1, totalNodes) &&
               checkHeap(root.right, 2 * index + 2, totalNodes);
    }

    static bool isHeap(Node root)
    {
        int totalNodes = countNodes(root);

        return checkHeap(root, 0, totalNodes);
    }

    static void Main()
    {
        Node root = new Node(97);
        root.left = new Node(46);
        root.right = new Node(37);
        root.left.left = new Node(12);
        root.left.right = new Node(3);
        root.right.left = new Node(7);
        root.right.right = new Node(31);

        Console.WriteLine(isHeap(root) ? "true" : "false");
    }
}
JavaScript
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Count total number of nodes
function countNodes(root) {
    if (root === null)
        return 0;

    return 1 + countNodes(root.left) +
           countNodes(root.right);
}

// Check completeness and max-heap property
function checkHeap(root, index, totalNodes) {
    if (root === null)
        return true;

    // Check if the tree is complete
    if (index >= totalNodes)
        return false;

    // Check max-heap property
    if (root.left !== null &&
        root.data < root.left.data)
        return false;

    if (root.right !== null &&
        root.data < root.right.data)
        return false;

    return checkHeap(root.left, 2 * index + 1, totalNodes) &&
           checkHeap(root.right, 2 * index + 2, totalNodes);
}

function isHeap(root) {
    const totalNodes = countNodes(root);

    return checkHeap(root, 0, totalNodes);
}

// Driver code
const root = new Node(97);
root.left = new Node(46);
root.right = new Node(37);
root.left.left = new Node(12);
root.left.right = new Node(3);
root.right.left = new Node(7);
root.right.right = new Node(31);

console.log(isHeap(root) ? "true" : "false");

Output
true

Level Order Traversal - O(n) Time and O(n) Space

Use level order traversal (BFS) to check both conditions of a max-heap. While traversing level by level, verify the heap property and use a flag to ensure the tree remains complete.

Step by Step approach :

  • Start a level order traversal using a queue.
  • For each node, check that its value is greater than or equal to its children.
  • If a node is missing a left or right child, set a flag indicating that all following nodes must be leaf nodes.
  • If any later node has a child after the flag is set, the tree is not complete.
  • If any node violates the max-heap property, return false.
  • If the entire traversal completes without violations, return true.
C++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

// Node Structure
class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int k) {
        data = k;
        left = nullptr;
        right = nullptr;
    }
};

bool isHeap(Node* root) {
    queue<Node*> q;     
    q.push(root);
    
    // Flag indicates if a node
    // with missing children has been seen
    bool flag = false;   
  
    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();

        // Check left child
        if (temp->left) {
       
            // If a node with missing child was seen before 
            // or if left child is bigger than parent, the heap rules are broken
            if (flag || temp->left->data > temp->data) {
                return false;
            }
            q.push(temp->left);
        } 
        else {
            
            // Left child is missing; set
            //flag indicating last node encountered
            flag = true;
        }
      
        // Check right child
        if (temp->right) {
            
            // Same checks as left child
            if (flag || temp->right->data > temp->data) {
                return false;
            }
            q.push(temp->right);
        }
        else {
            
            // Right child is missing; set flag
            flag = true;
        }
    }
    return true; 
}

int main() {
    // Construct the Binary Tree
    //        97
    //       /  \
    //      46    37
    //     / \   / \
    //    12  3 7   31
    //   /  \
    //  6    9
    Node *root = new Node(97);
    root->left = new Node(46);
    root->right = new Node(37);
    root->left->left = new Node(12);
    root->left->right = new Node(3);
    root->right->left = new Node(7);
    root->right->right = new Node(31);
    root->left->left->left = new Node(6);
    root->left->left->right = new Node(9);

    if(isHeap(root)){
        cout << "true" << endl;
    }
    else {
        cout << "false" << endl;
    }

    return 0;
}
Java
import java.util.Queue;
import java.util.LinkedList;

// Node Structure
class Node {
    int data;
    Node left;
    Node right;

    Node(int k) {
        data = k;
        left = null;
        right = null;
    }
}

public class GFG {

    public static boolean isHeap(Node root) {
        Queue<Node> q = new LinkedList<>();
        q.add(root);
         // Flag indicates if a node
         //with missing children has been seen
        boolean flag = false;   

        while (!q.isEmpty()) {
            Node temp = q.poll();

            // Check left child
            if (temp.left != null) {
                // If a node with missing child was seen before 
                // or if left child is bigger than parent, the heap rules are broken
                if (flag || temp.left.data > temp.data) {
                    return false;
                }
                q.add(temp.left);
            } 
            else {
                // Left child is missing; set
                //flag indicating last node encountered
                flag = true;
            }

            // Check right child
            if (temp.right != null) {
                // Same checks as left child
                if (flag || temp.right.data > temp.data) {
                    return false;
                }
                q.add(temp.right);
            }
            else {
                // Right child is missing; set flag
                flag = true;
            }
        }
        return true; 
    }

    public static void main(String[] args) {
        // Construct the Binary Tree
        //        97
        //       /  \
        //      46    37
        //     / \   / \
        //    12  3 7   31
        //   /  \
        //  6    9
        Node root = new Node(97);
        root.left = new Node(46);
        root.right = new Node(37);
        root.left.left = new Node(12);
        root.left.right = new Node(3);
        root.right.left = new Node(7);
        root.right.right = new Node(31);
        root.left.left.left = new Node(6);
        root.left.left.right = new Node(9);

        if(isHeap(root)){
            System.out.println("true");
        }
        else {
            System.out.println("false");
        }
    }
}
Python
from collections import deque

# Node Structure
class Node:
    def __init__(self, k):
        self.data = k
        self.left = None
        self.right = None

def isHeap(root):
    q = deque()
    q.append(root)
     # Flag indicates if a node
     #with missing children has been seen
    flag = False

    while q:
        temp = q.popleft()

        # Check left child
        if temp.left:
            # If a node with missing child was seen before 
            # or if left child is bigger than parent, the heap rules are broken
            if flag or temp.left.data > temp.data:
                return False
            q.append(temp.left)
        else:
            # Left child is missing; set
            #flag indicating last node encountered
            flag = True

        # Check right child
        if temp.right:
            # Same checks as left child
            if flag or temp.right.data > temp.data:
                return False
            q.append(temp.right)
        else:
            # Right child is missing; set flag
            flag = True

    return True

if __name__ == "__main__":
    # Construct the Binary Tree
    #        97
    #       /  \
    #      46    37
    #     / \   / \
    #    12  3 7   31
    #   /  \
    #  6    9
    root = Node(97)
    root.left = Node(46)
    root.right = Node(37)
    root.left.left = Node(12)
    root.left.right = Node(3)
    root.right.left = Node(7)
    root.right.right = Node(31)
    root.left.left.left = Node(6)
    root.left.left.right = Node(9)

    if isHeap(root):
        print("true")
    else:
        print("false")
C#
using System;
using System.Collections.Generic;

// Node Structure
class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int k) {
        data = k;
        left = null;
        right = null;
    }
}

class GFG {

    static bool isHeap(Node root) {
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
         // Flag indicates if a node
         //with missing children has been seen
        bool flag = false;

        while (q.Count > 0) {
            Node temp = q.Dequeue();

            // Check left child
            if (temp.left != null) {
                // If a node with missing child was seen before 
                // or if left child is bigger than parent, the heap rules are broken
                if (flag || temp.left.data > temp.data) {
                    return false;
                }
                q.Enqueue(temp.left);
            } 
            else {
                // Left child is missing; set
                //flag indicating last node encountered
                flag = true;
            }

            // Check right child
            if (temp.right != null) {
                // Same checks as left child
                if (flag || temp.right.data > temp.data) {
                    return false;
                }
                q.Enqueue(temp.right);
            }
            else {
                // Right child is missing; set flag
                flag = true;
            }
        }
        return true;
    }

    static void Main(string[] args) {
        
        // Construct the Binary Tree
        //        97
        //       /  \
        //      46    37
        //     / \   / \
        //    12  3 7   31
        //   /  \
        //  6    9
        Node root = new Node(97);
        root.left = new Node(46);
        root.right = new Node(37);
        root.left.left = new Node(12);
        root.left.right = new Node(3);
        root.right.left = new Node(7);
        root.right.right = new Node(31);
        root.left.left.left = new Node(6);
        root.left.left.right = new Node(9);

        if(isHeap(root)){
            Console.WriteLine("true");
        }
        else {
            Console.WriteLine("false");
        }
    }
}
JavaScript
// Node Structure
class Node {
    constructor(k) {
        this.data = k;
        this.left = null;
        this.right = null;
    }
}

// Custom Queue Implementation
class Queue {
    constructor() {
        this.items = [];
        this.frontIndex = 0;
    }

    enqueue(element) {
        this.items.push(element);
    }

    dequeue() {
        if (this.isEmpty()) return null;
        return this.items[this.frontIndex++];
    }

    isEmpty() {
        return this.frontIndex >= this.items.length;
    }
}

function isHeap(root) {
    let q = new Queue();
    q.enqueue(root);
    
    // Flag indicates if a node
    // with missing children has been seen
    let flag = false;

    while (!q.isEmpty()) {
        let temp = q.dequeue();

        // Check left child
        if (temp.left) {
            
            // If a node with missing child was seen before 
            // or if left child is bigger than parent, the heap rules are broken
            if (flag || temp.left.data > temp.data) {
                return false;
            }
            q.enqueue(temp.left);
        } 
        else {
            
            // Left child is missing; set
            // flag indicating last node encountered
            flag = true;
        }

        // Check right child
        if (temp.right) {
            // Same checks as left child
            if (flag || temp.right.data > temp.data) {
                return false;
            }
            q.enqueue(temp.right);
        }
        else {
            // Right child is missing; set flag
            flag = true;
        }
    }
    return true;
}

// Driver Code
// Construct the Binary Tree
//        97
//       /  \
//      46    37
//     / \   / \
//    12  3 7   31
//   /  \
//  6    9
let root = new Node(97);
root.left = new Node(46);
root.right = new Node(37);
root.left.left = new Node(12);
root.left.right = new Node(3);
root.right.left = new Node(7);
root.right.right = new Node(31);
root.left.left.left = new Node(6);
root.left.left.right = new Node(9);

if (isHeap(root)) {
    console.log("true");
} else {
    console.log("false");
}

Output
true
Comment