Code Logo

Tree Find Parent Index

Published at25 Jul 2026
Tree Traversal Easy 1 views
Like0

Given an array representing a complete binary tree in level-order and a node's index, find the index of its parent node. In the array representation, the parent of node at index i is at index floor((i-1)/2). If the node is the root (index 0), return -1.

For example, in the tree [1, 2, 3, 4, 5], the parent of node at index 1 is at index 0. The parent of node at index 3 is at index 1. The root (index 0) has no parent — return -1.

The parent-child relationship in an array-based binary tree follows a fixed formula. For any node at index i, its parent is at (i-1)//2. This formula works for both left children (odd indices) and right children (even indices).

The solution checks if the node is the root (i == 0) and returns -1 in that case. Otherwise, it computes and returns (i-1)//2.

Edge cases include the root node (return -1), invalid indices that are out of bounds (return -1), and nodes at index 1 or 2 (both have parent at index 0).

Example Input & Output

Example 1
Input
[1,2,3,4,5],3
Output
1
Explanation

Parent of index 3 is index 1

Example 2
Input
[1,2,3,4,5],1
Output
0
Explanation

Parent of index 1 is index 0

Example 3
Input
[1,2,3],2
Output
0
Explanation

Parent of index 2 is index 0

Example 4
Input
[1,2,3,4,5],0
Output
-1
Explanation

Root has no parent

Example 5
Input
[1,2,3,4,5],4
Output
1
Explanation

Parent of index 4 is index 1

Algorithm Flow

Recommendation Algorithm Flow for Tree Find Parent Index

Solution Approach

Return the parent index using the formula (i-1)/2, or -1 for the root or invalid indices.

function parentIndex(arr, i)
  if i <= 0 or i >= length(arr) then return -1
  return floor((i - 1) / 2)

If the index is 0 (the root) or out of bounds, return -1 to indicate no parent exists. Otherwise, compute (i-1)//2 using integer division. This formula works for both left children (odd i) and right children (even i) because the integer division truncates downward correctly.

Time complexity is O(1), space complexity is O(1).

Best Answers

java
class Solution {
    public int solution(int[] nums, int i) {
        return i<=0||i>=nums.length?-1:(i-1)/2;
    }
}