26. Is Binary Tree Heap
The problem can be found at the following link: 🔗 Question Link
🧩 Problem Description
Given a binary tree, determine whether it satisfies the properties of a Max-Heap.
A binary tree is a Max-Heap if:
Completeness: All levels of the tree are completely filled except possibly the last, which is filled from left to right.
Heap Property: The value of every node is greater than or equal to the values of its children.
📘 Examples
Example 1:
Input:
root[] = [97, 46, 37, 12, 3, 7, 31, 6, 9]
Output:
true
Explanation:
All levels are completely filled and the parent is always greater than or equal to children.
Example 2:
Input:
root[] = [97, 46, 37, 12, 3, 7, 31, N, 2, 4]
Output:
false
Explanation:
The tree is not complete and violates the max-heap property.
🔒 Constraints
$1 \leq \text{Number of Nodes} \leq 10^3$
$1 \leq \text{node->data} \leq 10^3$
✅ My Approach:
Recursive Count + Position Check
This approach combines:
Counting the number of nodes in the tree.
Verifying that the binary tree is complete and satisfies heap order property using a recursive index simulation.
Algorithm Steps:
Recursively count the total number of nodes
nin the tree.Traverse the tree with a recursive function using the theoretical array index of a complete binary tree (
i):If any node is placed at an index
i >= n, then it's not complete.Also, check if each node’s value is greater than its children’s.
If all checks pass, return
true.
🧮 Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where
nis the number of nodes in the binary tree, as each node is visited once.Expected Auxiliary Space Complexity: O(h), where
his the height of the binary tree due to recursion stack usage.
💡 Code (C)
🧠 Code (C++)
🧑💻 Code (Java)
🐍 Code (Python)
🧠 Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: 📬 Any Questions?. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated