Binary Heap Children Index Calculator
A binary heap stores a tree inside a flat array, so navigating from a parent node requires a small but important index calculation.
Run — free
This calculator returns the exact array positions of the left and right children for a supplied node. Select either zero-based indexing, common in programming languages, or one-based indexing, often used in textbooks and pseudocode. The result is deterministic, immediate, and validated to prevent invalid roots or arithmetic beyond JavaScript's safe integer range.
Choose the indexing scheme before applying the formula
Binary heaps have the same tree structure regardless of how an array is numbered, but the child formulas depend on where numbering begins. With zero-based indexing, the root occupies index 0. The left child of a node at index i is therefore at 2i + 1, while the right child is at 2i + 2. With one-based indexing, the root occupies index 1, so the formulas become 2i for the left child and 2i + 1 for the right child. Select the scheme that matches the array or algorithm you are inspecting; changing schemes without changing the node index refers to a different physical position. The calculator echoes the selected scheme and original node index beside both results, making the interpretation explicit. This is especially useful when comparing source code with a textbook, because many languages naturally use zero-based arrays while educational explanations may reserve position 0 and begin the heap at position 1. Confirming the convention first prevents an otherwise plausible off-by-one result.
Enter a valid node index and read both child positions
Provide the integer position of the parent node and select the array index scheme. For a zero-based heap, the node index may be 0 or any larger safe integer. For a one-based heap, it must be at least 1 because index 0 is outside that convention. The response supplies left_child_index and right_child_index as integers that can be used directly to inspect an array, construct a traversal, or verify an implementation. These values are structural positions, not proof that elements actually exist at those positions. A heap containing fewer elements may have neither child, or it may contain only the left child at the end of its array. Compare each returned index with the array length before dereferencing it in code. Under zero-based indexing, a child exists only when its index is less than the array length. Under one-based indexing, the correct boundary depends on whether position 0 is physically reserved, so compare against the representation used by your program. This separation keeps the calculation precise without making assumptions about heap size.
Use the result to test and debug heap operations
Child indices are fundamental to sift-down, heapify, priority queue removal, and tree visualization. During sift-down, an implementation calculates both positions, checks which children are present, compares their stored priorities, and swaps the parent with the appropriate child when the heap property is violated. A wrong indexing convention can skip the true left child, read beyond the array, or compare unrelated elements while still producing code that looks mathematically reasonable. This calculator provides a quick independent check for examples, unit tests, interview exercises, and code reviews. Try the root, an internal node, and a node near the end of the heap to cover the most revealing cases. The calculation accepts only safe integers and rejects results that would exceed the exact integer range, avoiding silently rounded indices for unrealistically large inputs. It performs no network requests and uses no random or time-dependent values. The browser calculation and API handler share the same pure function, so identical input produces identical output in either environment for $0.002 per API request.
What you can do with it
Debug a sift-down implementation
Verify that a priority queue examines the correct two array positions after removing its root.
Convert textbook formulas into code
Compare one-based pseudocode with a zero-based programming language without introducing an off-by-one error.
Create heap unit-test fixtures
Generate expected child positions for roots, internal nodes, and boundary cases in deterministic tests.
FAQ
What formulas are used for zero-based indexing?
For a node at index i, the left child is at 2i + 1 and the right child is at 2i + 2.
What formulas are used for one-based indexing?
For a node at index i, the left child is at 2i and the right child is at 2i + 1.
Does a returned index guarantee that the child exists?
No. The result gives structural positions. Compare each position with the actual heap array bounds before reading an element.
Why is node index zero invalid in one-based mode?
A one-based heap starts its root at position 1, so position 0 is not a node in that indexing scheme.
How much does the API calculation cost?
Each API request costs $0.002. The same deterministic calculation can also run in the browser.
For developers — API access
Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.
API endpoint
Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.
Call it from your stack
curl -X POST https://api.kit.forhosting.com/dev/heap-children-index \
-H "Authorization: Bearer $KIT_KEY" \
-H "Content-Type: application/json" \
-d '{"node_index":5}'const res = await fetch("https://api.kit.forhosting.com/dev/heap-children-index", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.KIT_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
"node_index": 5
})
});
const { task_id } = await res.json();import os, requests
res = requests.post(
"https://api.kit.forhosting.com/dev/heap-children-index",
headers={"Authorization": f"Bearer {os.environ['KIT_KEY']}"},
json={
"node_index": 5
},
)
task_id = res.json()["task_id"]<?php
$res = file_get_contents("https://api.kit.forhosting.com/dev/heap-children-index", false, stream_context_create([
"http" => [
"method" => "POST",
"header" => "Authorization: Bearer " . getenv("KIT_KEY") . "\r\nContent-Type: application/json",
"content" => '{"node_index":5}',
],
]));
$task = json_decode($res, true);body := bytes.NewBufferString(`{"node_index":5}`)
req, _ := http.NewRequest("POST", "https://api.kit.forhosting.com/dev/heap-children-index", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("KIT_KEY"))
req.Header.Set("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)Example request
{
"node_index": 5
}Example response
{
"task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
"type": "dev.heap_children_index",
"status": "queued",
"_links": {
"result": "/tasks/tsk_…/result"
}
}The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.
Pricing
Published price — no tokens, no invented credits. A failed task is never charged.
Errors
| HTTP | Code | Meaning |
|---|---|---|
401 | unauthorized | Missing or invalid API key. |
402 | insufficient_balance | Your balance doesn't cover the task price. |
404 | unknown_type | That task type doesn't exist. |
429 | rate_limited | Too many requests. Use the webhook instead of polling. |