Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PYTHON 3 PLEASE FOLLOW INSTRUCTIONS COMPLETE CODE Problem : Complete the functio

ID: 3712438 • Letter: P

Question

PYTHON 3 PLEASE FOLLOW INSTRUCTIONS

COMPLETE CODE

Problem : Complete the function treeToArrayBFS() to take in a root of a binary tree, and return an array containing the values of the nodes level by level, from right to left.

CODE :

class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
  
def treeToArray(root):
# TODO
  
root = Node(7)
root.left = Node(4)
root.left.left = Node(1)
root.left.right = Node(5)

root.right = Node(10)
root.right.right = Node(13)
print(treeToArray(root)) # has to print [7, 10, 4, 13, 5, 1]

Example 4 10 1 5 13 # when going right to left through each level: # the 1st level yields 7 # the 2nd level yields 10, 4 # the 3rd level yields 13, 5, 1 # putting them all together, yields [7, 10, 4, 13, 5, 1]

Explanation / Answer

class Node:

    def __init__(self, value):

        self.value = value

        self.left = None

        self.right = None

def height(root):

    if root != None:

   

        # get the height of left subtree

        l = height( root.left )

       

        # get the height of right subtree

        r = height( root.right )

       

        # if height of left subtree is more

        if l >= r:

       

            return l + 1

           

        # if height of right subtree is more

        else:

       

          return r + 1

   

    else:

   

        return 0

       

def treeToArray(root):

   

    # get the height of the tree

    ht = height(root)

   

    arr = []

   

    for i in range( 1 , ht + 1 ):

       

        level_order( root , arr , i )

       

    return arr

   

   

def level_order(root, arr, level):

    if root == None:

   

        return

       

    if level == 1:

   

        arr.append(root.value)

       

    elif level > 1:

   

        # traverse right subtree

        level_order( root.right , arr , level - 1 )

       

        # traverse left subtree

        level_order( root.left , arr , level - 1 )

root = Node(7)

root.left = Node(4)

root.left.left = Node(1)

root.left.right = Node(5)

root.right = Node(10)

root.right.right = Node(13)

print(treeToArray(root)) # has to print [7, 10, 4, 13, 5, 1]