Implement AVL tree preorder traversal with only self argument

82 Views Asked by At

For this assignment I'm not allowed to edit the method or the calling of it in the driver code, and it only takes a self argument. I'm having a bit of a brain lapse as I can't figure a way to run the method recursively for the left and right nodes.

Node setup class below

# This is the Node class init within AVl Tree Class.
      

        def __init__(self, val):
            # There are 4 attributes in each tree Node:
            # 1. A piece of data: self.val. (You may consider self.val is an integer here.)
            # 2. A pointer to its left child, which initially points to None.
            # 3. A pointer to its right child, which initially points to None.
            # 4. The height of this node: self.height.
            

            ####################    DO NOT CHANGE THIS   ####################
            self.val = val
            self.left = None
            self.right = None
            self.height = 0

Avl tree init below

def __init__(self, root = None):
        # In most of the designs, a tree is just a pointer to its root.
        # We use the same design here.

        ####################    DO NOT CHANGE THIS   ####################
        self.root = root

obviously incorrect traversal method below

 def preorder_tree_walk(self) -> []:
            print(self.root.val)
        if self.root.left:
            print(self.preorder_tree_walk(self.root.left)) #doesnt work, only self argument#
            if self.root.right:
                print(self.preorder_tree_walk(self.root.right)) #doesnt work, only self argument#

This seems to be relatively simple but I am coming up empty brained.

1

There are 1 best solutions below

0
zburner On

**Solution: created a list and a method within **

def preorder_tree_walk(self) -> []:

    list1 = []

    def rec_preorder_tree_walk(x):
        if x is not None:
            list1.append(x)
            rec_preorder_tree_walk(x.left)
            rec_preorder_tree_walk(x.right)

    rec_preorder_tree_walk(self.root)
    return list1