简体   繁体   中英

Printing the left and right child of a parent from a heap.

I have a list that represents a heap show below.

L = [8,4,7,2,3,1] 

I need to write a function that asks the user to input the position of a parent and then the function will print the value of the parent, left child and right child or false if the parent doesn't have children.

I tried the following code to begin with but I just get an error.

position = int(input("Enter the position: "))

L = [8,7,2,3,1]

print("Parent:",heapList[position])

def children(L, position):
    for i in L:
        if L[2*i+1] not in L:
            return False
        else:
            print("Left Child",L[2*i+1])

children(L, position)

When the user enters 0 as the position input an example of the output should look like this:

Parent: 8
Left child: 4
Right child: 7

You can avoid the loop by using functions such as these for truth statements.

def has_childern(self):
    return self.right_child or self.left_child

def has_both_childern(self):
    return self.right_child and self.left_child

And then just use a nested if, as an example.

if current_node.has_both_childern():
...
elif current_node.has_left_child():
...

Code should look like this:

L_heap = [8,4,7,2,3,1]
def children(L, position):
    if position > len(L) - 1 :
       print("There is no node at this heap position", position)
       return
    else:
       print("Parent", L[position]
    if (2*position+1) > len(L)-1:
        print("No childs")
        return
    else:
        print("Left Child",L[2*position+1])
        if not((2*position+2) > len(L)-1):
           print("Right Child",L[2*position +2])
    return

children(L_heap, 0)
children(L_heap, 5)
children(L_heap, 3)
children(L_heap, 8)

Output:

Parent 8
Left Child 4
Right Child 7
Parent 1
No childs
Parent 2
No childs
There is no node at this heap position 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM