1. Brute Force — Recursive Tree Traversal
Intuition
At index i, check if left child exists and is smaller than arr[i]; if so return false. Do the same for right child. Then recursively call isMinHeap for left and right children.
When to apply: When understanding the property through tree recursion.
Algorithm
- Step 1: Base case: if index >= n, return true.
- Step 2: If 2*i + 1 < n and arr[i] > arr[2*i + 1], return false.
- Step 3: If 2*i + 2 < n and arr[i] > arr[2*i + 2], return false.
- Step 4: Return isMinHeap(2*i + 1) && isMinHeap(2*i + 2).
#include <iostream>#include <vector>using namespace std; class Solution {public: bool isMinHeapHelper(const vector<int>& arr, int n, int i) { if (i >= n) return true; int left = 2 * i + 1; int right = 2 * i + 2; if (left < n && arr[i] > arr[left]) return false; if (right < n && arr[i] > arr[right]) return false; return isMinHeapHelper(arr, n, left) && isMinHeapHelper(arr, n, right); } bool isMinHeap(const vector<int>& arr) { return isMinHeapHelper(arr, arr.size(), 0); }}; int main() { Solution sol; vector<int> arr = {10, 15, 14, 25, 30}; cout << "Is Min Heap (Recursive): " << (sol.isMinHeap(arr) ? "true" : "false") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— O(N) to visit all nodes. - Space complexity:
O(log N)— O(log N) for the recursion stack.
Why Brute Force Doesn't Scale:
Queue BFS incurs memory allocation penalties. The direct loop has zero memory overhead and optimal cache locality.
Validating an array of 107 elements takes ~10ms iteratively vs ~250ms with queue BFS.