Problem:
Complete Binary Tree A complete binary tree is a binary tree in which every internal node has two children and all leaves have the same depth. A binary tree in which if last level is not completely filled but all nodes (leaves) are pushed across to the left, is also (nearly) a complete binary tree. A binary heap data structure is an array that can be viewed as a nearly complete binary tree as shown in the following figure.   Each node of a nearly complete binary tree corresponds to an element of the array that stores the value in the node. An array $A$ that represents a binary heap has the heap size $H$, the number of elements in the heap, and each element of the binary heap is stored into $A[1...H]$ respectively. The root of the tree is $A[1]$, and given the index $i$ of a node, the indices of its parent $parent(i)$, left child $left(i)$, right child $right(i)$ can be computed simply by $\lfloor i / 2 \rfloor$, $2 \times i$ and $2 \times i + 1$ respectively. Write a program which reads a binary heap represented by a nearly complete binary tree, and prints properties of nodes of the binary heap in the following format: node $id$: key = $k$, parent key = $pk$, left key = $lk$, right key = $rk$, $id$, $k$, $pk$, $lk$ and $rk$ represent id (index) of the node, value of the node, value of its parent, value of its left child and value of its right child respectively. Print these properties in this order. If there are no appropriate nodes, print nothing. Input In the first line, an integer $H$, the size of the binary heap, is given. In the second line, $H$ integers which correspond to values assigned to nodes of the binary heap are given in order of node id (from $1$ to $H$). Output Print the properties of the binary heap in the above format from node $1$ to $H$ in order. Note that, the last character of each line is a single space character.  Constraints  $H \leq 250$  $-2,000,000,000 \leq$ value of a node $\leq 2,000,000,000$  Sample Input 1 5
7 8 1 2 3 Sample Output 1 node 1: key = 7, left key = 8, right key = 1, 
node 2: key = 8, parent key = 7, left key = 2, right key = 3, 
node 3: key = 1, parent key = 7, 
node 4: key = 2, parent key = 8, 
node 5: key = 3, parent key = 8, Reference Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution (Python):


def decode_heap(target_list):
    for i, key in enumerate(target_list):
        node_index = i + 1
        parent_index = int(node_index / 2) - 1
        parent = ""
        if not parent_index < 0:
            parent = " parent key = " + str(target_list[parent_index]) + ","
            
        left_index = node_index * 2 - 1
        left = ""
        if left_index < len(target_list):
            left = " left key = {},".format(target_list[left_index])
            
        right_index = node_index * 2
        right = ""
        if right_index <  len(target_list):
            right = " right key = {},".format(target_list[right_index])

        print("node {}: key = {},{}{}{} ".format(node_index, key, parent, left, right))

        
def main():
    n_nodes = int(input())
    target_list = [int(a) for a in input().split()]
    decode_heap(target_list)
    
if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
heap = [-1] + list(map(int,input().split()))

for i in range(1,n+1):
    print("node {}: key = {}, " .format(i, heap[i]), end = '')
    if i!=1:
        print("parent key = {}, " .format(heap[i//2]), end = '')
    if i*2<=n:
        print("left key = {}, " .format(heap[i*2]), end ='')
    if i*2+1<=n:
        print("right key = {}, ".format(heap[i*2+1]), end='')
    print()

Solution (Python):
import sys

H = int(input())
heap = [None] + [int(i) for i in input().split()]

for i in range(1, H + 1):
    if i == 1:
        if 2 * i <= H and 2*i + 1 <= H:
            print('node {}: key = {}, left key = {}, right key = {}, '.format(
                    i, heap[i], heap[2 * i], heap[2*i + 1]))
        elif 2 * i <= H:
            print('node {}: key = {}, left key = {}, '.format(
                    i, heap[i], heap[2 * i]))
        else:
            print('node {}: key = {}, '.format(
                    i, heap[i]))
    elif 2 * i <= H and 2*i + 1 <= H:
        print('node {}: key = {}, parent key = {}, left key = {}, right key = {}, '.format(
                    i, heap[i], heap[i // 2], heap[2 * i], heap[2*i + 1]))
    elif 2 * i <= H:
        print('node {}: key = {}, parent key = {}, left key = {}, '.format(
                    i, heap[i], heap[i // 2], heap[2 * i]))
    else:
        print('node {}: key = {}, parent key = {}, '.format(
                    i, heap[i], heap[i // 2]))

Solution (Python):
n = int(input())
heap = list(map(int, input().split()))
for i in range(len(heap)):
    out = 'node {}: key = {}, '.format(i + 1, heap[i])
    parent = (i - 1) // 2
    out += 'parent key = {}, '.format(heap[parent]) if parent >= 0 else ''
    left = (2 * i) + 1
    out += 'left key = {}, '.format(heap[left]) if left < len(heap) else ''
    right = (2 * i) + 2
    out += 'right key = {}, '.format(heap[right]) if right < len(heap) else ''
    print(out)

Solution (Python):
if __name__ == '__main__':
    N = input()
    heap_array = [int(i) for i in input().split()]

    for i in range(len(heap_array)):
        print("node {}: key = {}, ".format(i+1, heap_array[i]), end='')
        if (i-1)//2 != -1 :
            print("parent key = {}, ".format(heap_array[(i-1)//2]), end='')
        if 2*i+1 < len(heap_array):
            print("left key = {}, ".format(heap_array[2*i+1]), end='')

        if 2*i+2 < len(heap_array):
            print("right key = {}, ".format(heap_array[2*i+2]), end='')
        print('')

Solution (Python):

n = int(input())
data = list(input().split())
data = [int(i) for i in data]

for i in range(n):
    print('node ',i+1,':',sep = '',end = '')
    print(' key = ',data[i],',',sep = '',end = '')

    if i != 0:
        print(' parent key = ',data[(i-1)//2],',',sep = '',end = '')
    
    if 2*i + 1 >= 0 and 2*i + 1 < n:
        print(' left key = ',data[2*i+1],',',sep = '',end = '')
    if 2*(i+1) >= 0 and 2*(i+1) < n:
        print(' right key = ',data[2*(i+1)],',',sep = '',end = '')

    print(' ')

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
for i in range(1, len(A) + 1):
  buff = "node {}: key = {}, ".format(i, A[i - 1])
  j = i // 2
  if j > 0: buff += "parent key = {}, ".format(A[j - 1])
  j = i * 2
  if j <= len(A): buff += "left key = {}, ".format(A[j - 1])
  j = i * 2 + 1
  if j <= len(A): buff += "right key = {}, ".format(A[j - 1])
  print(buff)

Solution (Python):
class Heap:
    def __init__(self, L):
        self.H = len(L)
        self.heap = L
        self.heap.insert(0, 0)

    def parent(self, i):
        return self.heap[i // 2]

    def left(self, i):
        return self.heap[2 * i]

    def right(self, i):
        return self.heap[2 * i + 1]

H = int(input())
L = list(map(int, input().split()))
heap = Heap(L)
for i in range(1, H + 1):
    print("node {}: key = {}, ".format(i, heap.heap[i]), end='')
    if i != 1:
        print("parent key = {}, ".format(heap.parent(i)), end='')
    if i * 2 <= H:
        print("left key = {}, ".format(heap.left(i)), end='')
    if i * 2 + 1 <= H:
        print("right key = {}, ".format(heap.right(i)), end='')
    print()

Solution (Python):
class HeapNode():
    def __init__(self):
        self.id = None
        self.key = None
        self.left = None
        self.right = None
        self.parent = None
    
    def show(self):
        print("node {0}: key = {1}, ".format(self.id,self.key), end="")
        if self.parent:
            print("parent key = {}, ".format(self.parent.key), end="")
        if self.left:
            print("left key = {}, ".format(self.left.key), end="")
        if self.right:
            print("right key = {}, ".format(self.right.key), end="")
        print("")

class HeapTree():
    def __init__(self, n):
        self.root = None
        self.n = n + 1
        self.T = [None] * (2 * n + 2)

    def insert(self, x):
        for i in range(len(x)):
            Node = HeapNode()
            if self.root is None:
                self.root = Node
            Node.id = i + 1
            Node.key = x[i]
            self.T[i+1] = Node
            
    def setPLR(self):
        for i in range(1, self.n):
            Node = self.T[i]
            Node.left = self.T[i * 2]
            Node.right = self.T[i * 2 + 1]
            Node.parent = self.T[i // 2]

    def TreePrint(self):
        for i in self.T[1 : self.n]:
            i.show()

n = int(input())
L = list(map(int, input().split()))
Tree = HeapTree(n)
Tree.insert(L)
Tree.setPLR()
Tree.TreePrint()

Solution (Python):
n = int(input())
xs = [int(i) for i in input().split()]
for i in range(n):
    ind = i + 1
    ret = "node " + str(ind) + ": key = " + str(xs[ind - 1])
    if ind != 1:
        parent = ind // 2 - 1
        ret += ", parent key = " + str(xs[parent])
    if n > 2 * i + 1:
        ret += ", left key = " + str(xs[2 * i + 1])
    if n > 2 * i + 2:
        ret += ", right key = " + str(xs[2*i + 2])
    ret += ", "
    print(ret)

Solution (Python):

n = int(input())
l = list(map(int, input().split()))

for i in range(n):
    id = i + 1
    ans = "node " + str(id) + ": key = " + str(l[id - 1])
    if id != 1:
        parent = id // 2 - 1
        ans += ", parent key = " + str(l[parent])
    if n > 2 * i + 1:
        ans += ", left key = " + str(l[2 * i + 1])
    if n > 2 * i + 2:
        ans += ", right key = " + str(l[2*i + 2])
    ans += ", "
    print(ans)

Solution (Python):
def print_heap():
    for i in range(n):
        if (i-1)//2 in range(n):
            if 2*i+1 in range(n):
                if 2*i+2 in range(n):
                    print("node {}: key = {}, parent key = {}, left key = {}, right key = {}, "
                          .format(i+1, heap[i], heap[(i-1)//2], heap[2*i+1], heap[2*i+2]))
                else:
                    print("node {}: key = {}, parent key = {}, left key = {}, "
                          .format(i+1, heap[i], heap[(i-1)//2], heap[2*i+1]))
            else:
                print("node {}: key = {}, parent key = {}, "
                      .format(i+1, heap[i], heap[(i-1)//2]))
        else:
            if 2*i+1 in range(n):
                if 2*i+2 in range(n):
                    print("node {}: key = {}, left key = {}, right key = {}, "
                          .format(i+1, heap[i], heap[2*i+1], heap[2*i+2]))
                else:
                    print("node {}: key = {}, left key = {}, "
                          .format(i+1, heap[i], heap[2*i+1]))
            else:
                print("node {}: key = {}, ".format(i+1, heap[i]))


if __name__ == "__main__":
    n = int(input())
    heap = list(map(int, input().split()))
    print_heap()

Solution (Python):
def main():
    n = input()
    k = map(int,raw_input().split())
    for i in range(1,n+1):
        print "node {0}: key = {1},".format(i,k[i-1]),
        p_id = i/2
        l_id = 2*i
        r_id = 2*i+1

        if 0 < p_id <= n:
            print "parent key = {0},".format(k[p_id-1]),
        if l_id <= n:
            print "left key = {0},".format(k[l_id-1]),
        if r_id <= n:
            print "right key = {0},".format(k[r_id-1]),
        print ""

if __name__ == "__main__":
    main()

Solution (Python):

import math

class Tree():
    def __init__(self, key):
        self.root = key

class Node():
    def __init__(self, id, key):
        self.id = id
        self.key = key
        self.parent = None
        self.left = None
        self.right = None

    def set_status(self, id, key):
        global node_list
        parent_id = math.floor(id/2)
        odd = id % 2
        self.parent = node_list[parent_id]
        if odd == 0:
            self.parent.left = self
        else:
            self.parent.right = self

def print_nodes():
    global node_list
    node_list.pop(0)
    for node in node_list:
        print("node {}: key = {}".format(node.id, node.key), end = "")
        if node.parent:
            print(", parent key = {}".format(node.parent.key), end = "")
        if node.left:
            print(", left key = {}".format(node.left.key), end = "")
        if node.right:
            print(", right key = {}".format(node.right.key), end = "")
        print(", ")

n = int(input())
input_num = list(map(int, input().split()))
node_list = [None]

for i, num in enumerate(input_num):
    i = i + 1 
    node = Node(i, num)
    node_list.append(node)

    if i == 1:
        tree = Tree(num)
    else:
        node.set_status(i, num)

print_nodes()

Solution (Python):

def main():

    """ ????????? """
    H = int(input().strip())
    hkeys = list(map(int,(input().split())))
    for i in range(H):
        txts = []
        id = i + 1
        txts.append("node {}: key = {},".format(id, hkeys[i]))
        parent = int(id / 2)
        if parent != 0:
            txts.append("parent key = {},".format(hkeys[parent-1]))
        left = id * 2
        if left > 0 and left <= H:
            txts.append("left key = {},".format(hkeys[left-1]))
        right = left + 1
        if right > 0 and right <= H:
            txts.append("right key = {},".format(hkeys[right-1]))
        print("{} ".format(" ".join(txts)))

if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
H = list(map(int, input().split()))

for i in range(N):
    i += 1
    parent = i // 2
    left = i * 2
    right = i * 2 + 1
    t = "node {}: key = {}, ".format(i, H[i-1])
    
    if i > 1:
        t += "parent key = {}, ".format(H[parent-1])
    
    if left <= N:
        t += "left key = {}, ".format(H[left-1])
        
    if right <= N:
        t += "right key = {}, ".format(H[right-1])
    
    print(t)

Solution (Python):

import sys
from math import floor
sys.setrecursionlimit(100000)

N = int(input())
heap = [None] + [int(n) for n in input().split()]

for i, h in enumerate(heap[1:]):
    i += 1
    text = "node {}: key = {}, ".format(i, h)
    if i != 1:
        text += "parent key = {}, ".format(heap[floor(i/2)])
    if 2 * i <= N:
        text += "left key = {}, ".format(heap[2*i])
    if 2 * i + 1 <= N:
        text += "right key = {}, ".format(heap[2*i + 1])
    print(text)

Solution (Python):
class Node():
    def __init__(self, id, key, parent, left, right):
        self.id = id
        self.key = key
        self.parent = parent
        self.left = left
        self.right = right
    def show(self):
        print 'node %d: key = %d,' % (self.id, self.key),
        if self.parent:
            print 'parent key = %d,' % self.parent, 
        if self.left:
            print 'left key = %d,' % self.left,
        if self.right:
            print 'right key = %d,' % self.right,
        print ''

def calcParent(key):
    if key == 1:
        return None
    else:
        return data[int(key/2) - 1]

def calcLeft(key):
    if 2 * key < n + 1:
        return data[2 * key - 1]
    return None

def calcRight(key):
    if 2 * key < n:
        return data[2 * key]
    return None
        
n = int(raw_input())
data = map(int, raw_input().split())
node_list = []
for i in range(n):
    this_id = i + 1
    node_list.append(Node(i+1, data[i], calcParent(this_id), calcLeft(this_id), calcRight(this_id)))

for i in node_list:
    i.show()

Solution (Python):
n = int(input())
h = [int(i) for i in input().split()]
for i in range(n):
    print('node %d: key = %d, ' %(i+1, h[i]), end='')
    if i != 0:
        print('parent key = %d, ' %(h[(i+1) // 2 - 1]), end='')
    li = 2 * i + 1
    if li < n:
        print('left key = %d, ' %(h[li]), end='')
    ri = 2 * i + 2
    if ri < n:
        print('right key = %d, ' %(h[ri]), end='')
    print('')

Solution (Python):
h = int(input())
key = list(map(int,input().split()))
key.insert(0,0)

for i in range(h):
    k = i + 1
    lk = 2*k
    rk = 2*k + 1
    pk = int(0.5*k)
    if k == 1:
        print("node {0}: key = {1}, left key = {2}, right key = {3}, ".format(k, key[k], key[lk], key[rk]))
    elif lk > h:
        print("node {0}: key = {1}, parent key = {2}, ".format(k, key[k], key[pk]))
    elif rk > h:
        print("node {0}: key = {1}, parent key = {2}, left key = {3}, ".format(k, key[k], key[pk], key[lk]))
    else:
        print("node {0}: key = {1}, parent key = {2}, left key = {3}, right key = {4}, ".format(k, key[k], key[pk], key[lk], key[rk]))

Solution (Python):



def complete_binary_tree(tree, n):
    for i in range(1, n + 1):
        node = "node {0}: ".format(i)
        key = "key = {0}, ".format(tree[i-1])
        if i // 2 == 0:
            parent = ""
        else:
            parent = "parent key = {0}, ".format(tree[(i // 2) - 1])

        if n >= (i * 2) + 1:
            left = "left key = {0}, ".format(tree[(i * 2) - 1])
            right = "right key = {0}, ".format(tree[(i * 2)])
        elif n >= (i * 2):
            left = "left key = {0}, ".format(tree[(i * 2) - 1])
            right = ""
        else:
            left = ""
            right = ""

        print(node + key + parent + left + right)


if __name__ == "__main__":
    n = int(input())
    tree = [int(n) for n in input().split()]
    complete_binary_tree(tree, n)

Solution (Python):



if __name__ == '__main__':

    H = int(input())
    A = [None] + [int(i) for i in input().split(" ")]

    def parent(i):
        return i // 2

    def left(i):
        return 2*i

    def right(i):
        return 2*i + 1

    for i in range(1, H+1):
        print("node {}: key = {},".format(i, A[i]), end=" ")
        if parent(i) >= 1:
            print("parent key = {},".format(A[parent(i)]), end=" ")
        if left(i) <= H:
            print("left key = {},".format(A[left(i)]), end=" ")
        if right(i) <= H:
            print("right key = {},".format(A[right(i)]), end=" ")
        print("")

Solution (Python):
H = int(input())
A = list(map(int, input().split()))
for i in range(H):
    s = f"node {i + 1}: key = {A[i]}, "
    if i != 0:
        s += f"parent key = {A[(i - 1) // 2]}, "
    if H > i * 2 + 1:
        s += f"left key = {A[i * 2 + 1]}, "
    if H > i * 2 + 2:
        s += f"right key = {A[i * 2 + 2]}, "
    print(s)

Solution (Python):
input()
A=[0]+input().split()
H=len(A)
for i in range(1,H):
 print(f'node {i}: key = {A[i]}, {f"parent key = {A[i//2]}, "if i//2>0 else""}{f"left key = {A[2*i]}, "if 2*i<H else""}{f"right key = {A[2*i+1]}, "if 2*i+1<H else""}')

Solution (Python):
input()
A=input().split()
H=len(A)
for i in range(H):
 print(f'node {i+1}: key = {A[i]}, {f"parent key = {A[(i-1)//2]}, "if i>0 else""}{f"left key = {A[2*i+1]}, "if 2*i+1<H else""}{f"right key = {A[2*i+2]}, "if 2*i+2<H else""}')

Solution (Python):
input()
A=[0]+input().split()
H=len(A)
for i in range(1,H):
 print(f'node {i}: key = {A[i]}, {f"parent key = {A[i//2]}, "if i>1 else""}{f"left key = {A[2*i]}, "if 2*i<H else""}{f"right key = {A[2*i+1]}, "if 2*i+1<H else""}')

Solution (Python):
k=' key = '
input()
A=[0]+input().split()
H=len(A)
for i in range(1,H):
 print(f'node {i}: key = {A[i]}, {"parent"+k+A[i//2]+", "if i>1 else""}{"left"+k+A[2*i]+", "if 2*i<H else""}{"right"+k+A[2*i+1]+", "if 2*i+1<H else""}')

Solution (Python):
k,e=' key = ',', '
input()
A=[0]+input().split()
H=len(A)
for i in range(1,H):
 print(f'node {i}: key = {A[i]}, {"parent"+k+A[i//2]+e if i>1 else""}{"left"+k+A[2*i]+e if 2*i<H else""}{"right"+k+A[2*i+1]+e if 2*i+1<H else""}')

Solution (Python):
input()
A=[0]+input().split()
H=len(A)
for i in range(1,H):
 print(f'node {i}: key = {A[i]}, {f"parent key = {A[i//2]}, "if i>1 else""}{f"left key = {A[2*i]}, "if 2*i<H else""}{f"right key = {A[2*i+1]}, "if 2*i+1<H else""}')

Solution (Python):
if __name__ == '__main__':
    _ = input()
    hoge = [int(x) for x in input().split()]
    
    for index_num, elem in enumerate(hoge):
        output = list()
        parent = (index_num+1) // 2 
        left_c = (index_num+1) * 2 -1
        right_c = left_c +1
        if parent == 0:
            flag = True
        else:
            flag = False
        if left_c >= len(hoge):
            left_c = -1
        if right_c >= len(hoge):
            right_c = -1
        if flag:
            parent = -1
        else:
            parent -= 1
        hoge.append('')
        output.append('node {}:'.format(index_num+1))
        output.append('key = {},'.format(elem))
        if hoge[parent] != '':
            output.append('parent key = {},'.format(hoge[parent]))
        if hoge[left_c] != '':
            output.append('left key = {},'.format(hoge[left_c]))
        if hoge[right_c] != '':
            output.append('right key = {},'.format(hoge[right_c]))
        print(' '.join(output) + ' ')
        hoge.pop()

Solution (Python):
n = int(input())

a = list(map(int, input().split()))

for i in range(n):
    node = i + 1
    key = a[i]
    out = "node {}: key = {}, ".format(node, key)
    out += "parent key = {}, ".format(a[(i - 1) // 2]) if (i-1)//2 >=0 else ""
    out += "left key = {}, ".format(a[i * 2 + 1]) if i*2 + 1 < n else ""
    out += "right key = {}, ".format(a[i * 2 + 2]) if i*2 + 2 < n else ""
    print(out)

Solution (Python):


n = int(input())
a = list(map(int, input().split())) 


for i in range(1, n+1):
    print("node {0:}: key = {1:}, ".format(i, a[i-1]), end = "")
    if 0 < i // 2:
        print("parent key = {0:}, ".format(a[i//2 - 1]), end = "")
    if 2 * i <= n:
        print("left key = {0:}, ".format(a[2*i - 1]), end = "")
    if 2 * i + 1 <= n:
        print("right key = {0:}, ".format(a[2*i]), end = "")
    print("")

Solution (Python):

class Heap:
    def __init__(self):
        self._nodes = []

    @classmethod
    def create(cls, li):
        heap = cls()
        heap._nodes = li
        return heap

    def __iter__(self):
        self.cur = 0
        return self

    def __next__(self):
        if self.cur >= len(self._nodes):
            raise StopIteration
        self.cur += 1

        node = self._nodes[self.cur-1]
        if self.cur//2 - 1 >= 0:
            parent = self._nodes[self.cur//2 - 1]
        else:
            parent = None

        if self.cur*2 - 1 < len(self._nodes):
            left = self._nodes[self.cur*2 - 1]
        else:
            left = None

        if self.cur*2 < len(self._nodes):
            right = self._nodes[self.cur*2]
        else:
            right = None

        return (node, parent, left, right)


def run():
    _ = int(input())

    nodes = [int(i) for i in input().split()]
    heap = Heap.create(nodes)

    for (i, node) in enumerate(heap):
        n, p, nl, nr = node
        s = "node {}: key = {}, ".format(i+1, n)
        if p is not None:
            s += "parent key = {}, ".format(p)
        if nl is not None:
            s += "left key = {}, ".format(nl)
        if nr is not None:
            s += "right key = {}, ".format(nr)

        print(s)


if __name__ == '__main__':
    run()

Solution (Python):
n = int(input())
a = [0] + list(map(int, input().split()))
def pi(i):
    global a, n
    s = f"node {i}: key = {a[i]}, "
    if i != 1:
        s += f"parent key = {a[int(i / 2)]}, "
    if i * 2 <= n:
        s += f"left key = {a[2 * i]}, "
        if i * 2 + 1 <= n:
            s += f"right key = {a[2 * i + 1]}, "
    print(s)

for i in range(1, n + 1):
    pi(i)

Solution (Python):
n = int(input())
H = list(map(int, input().split(' ')))

for i in range(n):
    node = i+1
    key = H[i]
    parent = H[int(node/2)-1] if node != 1 else None
    left = H[node*2-1] if node*2 <= n else None
    right = H[node*2] if node*2+1 <= n else None
    print('node %d: key = %d, '%(node, key), end='')
    if parent != None: print('parent key = %d, '%parent, end='')
    if left != None: print('left key = %d, '%left, end='')
    if right != None: print('right key = %d, '%right, end='')
    print('')

Solution (Python):
class NullNode():
    def __init__(self):
        self.id = None

null_node = NullNode()

class Node():
    def __init__(self, id):
        global null_node
        self.id = id
        self.parent = null_node
        self.left = null_node
        self.right = null_node

n = int(input())
node_list = [Node(id) for id in input().split()]

for i in range(n):
    node = node_list[i]
    node.left = node_list[2*i+1] if 2*i+1 < n else null_node
    node.right = node_list[2*i+2] if 2*i+2 < n else null_node
    if i != 0:
        node_list[i].parent = node_list[(i-1)//2]
    out_put = []
    out_put.append('node {}: '.format(i+1))
    out_put.append('key = {}, '.format(node.id))
    if node.parent.id is not None:
        out_put.append('parent key = {}, '.format(node.parent.id))
    if node.left.id is not None:
        out_put.append('left key = {}, '.format(node.left.id))
    if node.right.id is not None:
        out_put.append('right key = {}, '.format(node.right.id))
    print(''.join(out_put))

Solution (Python):

class BinaryHeap:
    def __init__(self, ary):
        self.nodes = []
        for i, key in enumerate(ary):
            id = i + 1
            parent = id // 2
            if parent:
                parent_key = ary[parent - 1]
            else:
                parent_key = None
            left = 2 * id
            right = 2 * id + 1
            if left <= len(ary):
                left_key = ary[left - 1]
            else:
                left_key = None
            if right <= len(ary):
                right_key = ary[right - 1]
            else:
                right_key = None
            self.nodes.append(Node(id, key, parent_key, left_key, right_key))

    def print(self):
        for node in self.nodes:
            print('node {}: key = {}, '.format(node.id, node.key), end='')
            if type(node.parent_key) == int:
                print('parent key = {}, '.format(node.parent_key), end='')
            if type(node.left_key) == int:
                print('left key = {}, '.format(node.left_key), end='')
            if type(node.right_key) == int:
                print('right key = {}, '.format(node.right_key), end='')
            print()


class Node:
    def __init__(self, id, key, parent_key, left_key, right_key):
        self.id = id
        self.key = key
        self.parent_key = parent_key
        self.left_key = left_key
        self.right_key = right_key


if __name__ == '__main__':
    H = int(input())
    ary = [int(_) for _ in input().split()]
    bh = BinaryHeap(ary)
    bh.print()

Solution (Python):
import math

h = int(input())
a = list(map(int,input().split()))

def parent(node):
    return math.floor(node/2)

def left(node):
    return 2*node

def right(node):
    return 2*node+1

for i in range(1,h+1):
    print('node {}: key = {}, '.format(i,a[i-1]),end='')
    if parent(i) > 0:
        print('parent key = {}, '.format(a[parent(i)-1]),end='')
    if left(i) <= h:
        print('left key = {}, '.format(a[left(i)-1]),end='')
    if right(i) <= h:
        print('right key = {}, '.format(a[right(i)-1]),end='')
    print()

Solution (Python):
n = int(input())
a = [0] + list(map(int, input().split()))
def pi(i):
    global a, n
    s = f"node {i}: key = {a[i]}, "
    if i != 1:
        s += f"parent key = {a[int(i / 2)]}, "
    if i * 2 <= n:
        s += f"left key = {a[2 * i]}, "
        if i * 2 + 1 <= n:
            s += f"right key = {a[2 * i + 1]}, "
    print(s)
 
for i in range(1, n + 1):
    pi(i)

Solution (Python):



def parent(i):
    return i//2

def left(i):
    return i*2

def right(i):
    return i*2+1

def main():
    H=int(input())
    a = [0] + list(map(int, input().split()))

    for i in range(H):
        i+=1
        print("node "+str(i)+": key = "+str(a[i])+", ",end="")
        if(parent(i)):
            print("parent key = "+str(a[parent(i)])+", ",end="")
        if(left(i)<=H):
            print("left key = "+str(a[left(i)])+", ",end="")
        if(right(i)<=H):
            print("right key = "+str(a[right(i)])+", ",end="")
        print()

    return 0

if __name__ == "__main__":
    main()

Solution (Python):
import math


def make_row(id, heap):
    s = "node " + str(id) + ": key = " + str(heap[id - 1]) + ", "
    length = len(heap)
    if 0 <= math.floor(id // 2) - 1 < length:
        s += "parent key = " + str(heap[math.floor(id // 2) - 1]) + ", "
    if 0 <= 2 * id - 1 < length:
        s += "left key = " + str(heap[2 * id - 1]) + ", "
    if 0 <= 2 * id < length:
        s += "right key = " + str(heap[2 * id]) + ", "
    return s


h = int(input())
heap = [int(x) for x in input().split()]

for id in range(1, h + 1):
    print(make_row(id, heap))

Solution (Python):

N = int(input())
nums = list(map(int,input().split()))

for ID,num in enumerate(nums,1):
    if 1 <= ID // 2 <= N:
        p = "parent key = {}, ".format(nums[ID // 2 - 1])
    else:
        p = ""
    if 1 <= 2 * ID <= N:
        l = "left key = {}, ".format(nums[2*ID - 1])
    else:
        l = ""
    if 1 <= 2 * ID + 1 <= N:
        r = "right key = {}, ".format(nums[2*ID])
    else:
        r = ""

    print("node {}: key = {}, ".format(ID,num) + p + l + r)

Solution (Python):
import sys

def parent(i, *d):
    tmp = i/2
    if tmp <=0 or tmp>=len(d): return None
    else: return d[tmp]

def left(i, *d):
    tmp = 2*i
    if tmp>=len(d): return None
    else: return d[tmp]
    
def right(i, *d):
    tmp = 2*i+1
    if tmp>=len(d): return None
    else: return d[tmp]

n = int(input())
i = 0
x = map(int, [0] + raw_input().split()) 
for i in range(1, len(x)):
    print "node %d: key = %d," % (i, x[i]),
    tmp = parent(i, *x)
    if tmp != None: print "parent key = %d," %(tmp),
    tmp = left(i, *x)
    if tmp != None: print "left key = %d," %(tmp),
    tmp = right(i, *x)
    if tmp != None: print "right key = %d," %(tmp),
    print ""

Solution (Python):

from __future__ import division, print_function
from sys import stdin

heap_size = int(stdin.readline())

heap = [int(s) for s in stdin.readline().split()]
for i, v in enumerate(heap, start=1):
    parent = heap[i//2 -1] if i > 1 else None
    left = heap[2*i -1] if 2*i <= heap_size else None
    right = heap[2*i] if 2*i+1 <= heap_size else None
    print('node {}: key = {}, '.format(i, v), end='')
    if parent:
        print('parent key = {}, '.format(parent), end='')
    if left:
        print('left key = {}, '.format(left), end='')
    if right:
        print('right key = {}, '.format(right), end='')
    print()

Solution (Python):
H = int(input())
A = [0] + list(map(int, input().split()))

for i in range(1, H+1):
    key = A[i]
    parent = A[i//2] if i//2 >= 1 and i//2 <= H else None
    left = A[2*i] if 2*i >= 1 and 2*i <= H else None
    right = A[2*i+1] if 2*i+1>=1 and 2*i+1 <= H else None
    ans = f"node {i}: key = {key}, "
    if parent is not None:
        ans += f"parent key = {parent}, "
    if left is not None:
        ans += f"left key = {left}, "
    if right is not None:
        ans += f"right key = {right}, "
    print(ans)

Solution (Python):
n = int(input())
a = [0] + input().split()

for i in range(1,n+1):
    print(f'node {i}: key = {a[i]}, ',end ="")
    print(f'parent key = {a[i//2]}, 'if i>1 else "",end = "")
    print(f'left key = {a[2*i]}, 'if 2*i<=n else "",end = "")
    print(f'right key = {a[2*i + 1]}, ' if  2*i + 1<=n  else "")