What's new

Help Add a new node on a heap tree(min/max)

Phrog

Forum Veteran
Elite
Joined
Jan 25, 2017
Posts
2,131
Reaction
1,379
Points
637
Eto nalang po ang kulang ko, kung paano mag add ng new node sa heap tree
Min and Max Heap, may na try po ako pero built-in function lang ng array
And as expected po, gumagana pero di po sya nag aappear pag ipiprint na
Nag hanap na din po ako sa google before nung insert or addnode functions
Kaso wala pong gumana, and kahit imodify ko po.
Balak ko po sana defined function na po. Thank you po in advance
eto po code:

Python:
#add node
        if command == 2:
            addnode = (int(input("Add node: ")))
            maxarr.insert(5, addnode)
            minarr.insert(5, addnode)

            maxHeap.build_max_heap(maxarr)
            minHeap.build_min_heap(minarr)

            userInput.tryAgain()

WHOLE CODE:
Python:
import os
import sys
class maxHeap:
    def max_heapify(maxarr,i):
        l = maxHeap.left(i)
        r = maxHeap.right(i)
        if l < len(maxarr) and maxarr[l] > maxarr[i]:
            largest = l
        else:
            largest = i
        if r < len(maxarr) and maxarr[r] > maxarr[largest]:
            largest = r
        if largest != i:
            maxarr[i], maxarr[largest] = maxarr[largest], maxarr[i]
            maxHeap.max_heapify(maxarr, largest)

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

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

    def build_max_heap(maxarr):
        n = int((len(maxarr) // 2)-1)
        for i in range(n, -1,-1):
            maxHeap.max_heapify(maxarr, i)

    #def maxInsert():

    def printmaxArray(maxarr, n):
        for i in range(n):
            print(maxarr[i], end = ' ')
        print()

    def maxDeleteRoot(maxarr: list):
        global n
        n = max(maxarr) # 9
        maxarr.pop(maxarr.index(n))
        maxHeap.build_max_heap(maxarr)
        print(maxarr)
        print("\nRemoved: " + str(n))

    def exitProgram():
        os.system('cls')
        print(f"THANK YOU FOR USUNG THE PROGRAM!")
        sys.exit()


class minHeap:
    def min_heapify(minarr, i):
        left = maxHeap.left(i)
        right = maxHeap.right(i)
        if left < len(minarr) and minarr[left] < minarr[i]:
            smallest = left
        else:
            smallest = i
        if right < len(minarr) and minarr[right] < minarr[smallest]:
            smallest = right
        if smallest != i:
            minarr[i], minarr[smallest] = minarr[smallest], minarr[i]
            minHeap.min_heapify(minarr, smallest)

    def printminArray(arr, n):
        for i in range(n):
            print(arr[i], end = ' ')
        print()

    def build_min_heap(minarr):
        n1 = int((len(minarr) // 2)-1)
        for k in range(n1, -1, -1):
            minHeap.min_heapify(minarr, k)

    #delete function
    def minDeleteRoot(minarr: list):
        n1 = min(minarr) # 1
        minarr.pop(minarr.index(n1))
        minHeap.build_min_heap(minarr)
        print(minarr)
        print("\nRemoved: " + str(n1))


class userInput:
    def tryAgain():
        choice = input("\nAgain?(y/n): ").lower()
        if choice not in ['y', 'n']:
            print('\nINVALID INPUT!')
            userInput.tryAgain()
        elif choice == 'y':
            userInput.enterCommand()
        else:
            maxHeap.exitProgram()

    #user input function
    def enterCommand():
        global maxarr
        global minarr
        global n
        global n1

        maxarr = [3,9,2,1,4,5]
        minarr  = [3,9,2,1,4,5]
        n = len(maxarr)
        n1 = len(minarr)
        command =  int(input("\nEnter Number[0 - 6]: "))
        if command == 2:
            addnode = (int(input("Add node: ")))
            maxarr.insert(5, addnode)
            minarr.insert(5, addnode)

            maxHeap.build_max_heap(maxarr)
            minHeap.build_min_heap(minarr)

            userInput.tryAgain()

        elif command == 4:
            print("\nMAX HEAP AFTER DELETION:")
            maxHeap.maxDeleteRoot(maxarr)

            print("\nMIN HEAP AFTER DELETION:")
            minHeap.minDeleteRoot(minarr)
            userInput.tryAgain()

        elif command == 6:
            maxHeap.build_max_heap(maxarr)
            print("\nMAX HEAP:")
            maxHeap.printmaxArray(maxarr, n1)

            minHeap.build_min_heap(minarr)
            print("\nMAX HEAP:")
            minHeap.printminArray(minarr, n1)
            userInput.tryAgain()
        
        elif command == 0:
           maxHeap.exitProgram()

DRIVER CODE:

Python:
from maxminheapcode import *
import time

time.sleep(0.5)
print("\t\t\t\tMENU FOR NON-LINER DATA STRUCTURE     ")
time.sleep(0.5)
print("=================================================================================================")
print("=\t\t\t\t\t<<[0] Exit>>                                            =")
print("=   <<ADDING ITEMS>>               <<DELETING ITEMS>>                <<PRINTING ITEMS>>         =")
print("= [1] Add items to BSTREE     [3] Delete items from BSTREE     [5] Print items from BSTREE      =")
print("= [2] Add items to HEAP TREE  [4] Delete items from HEAP TREE  [6] Print items from HEAP TREE   =")
print("=================================================================================================")
time.sleep(0.5)
userInput.enterCommand()

OUTPUT:
Python:
Enter Number[0 - 6]: 2
Add node: 7

Again?(y/n): y

Enter Number[0 - 6]: 6

MAX HEAP:   
9 4 5 1 3 2

MAX HEAP:
1 3 2 9 4 5
 
There is no specific method to add a node into a min and max heap tree in Python. However, the general steps to add a node into a heap tree are as follows:

1. Compare the value of the node to be added with the root node.
2. If the value of the node to be added is less than the value of the root node, then add the node to the left subtree.
3. If the value of the node to be added is greater than the value of the root node, then add the node to the right subtree.
4. Repeat step 1 for the subtree in which the node was added.
 
There is no specific method to add a node into a min and max heap tree in Python. However, the general steps to add a node into a heap tree are as follows:

1. Compare the value of the node to be added with the root node.
2. If the value of the node to be added is less than the value of the root node, then add the node to the left subtree.
3. If the value of the node to be added is greater than the value of the root node, then add the node to the right subtree.
4. Repeat step 1 for the subtree in which the node was added.
Thank you po, try ko po yan, and maulit po yung code di po ako nakagamit ng init
 
Uulitin ko nalang po from the start, na move po deadline. Thank you po ulit
 

Similar threads

Back
Top