I wonder, why one of the tree_to_list functions is outputting the elements in a different order, than the other one

Viewed 22

I think the title explains the question. Can somebody help?

class Node:

def __init__(self,value):
    
    self.value = value
    self.left = None
    self.right = None
        
def tree_to_list(self):
    
    if self.left != None:
        if self.right != None:
            return [self.value] + self.left.tree_to_list() + self.right.tree_to_list()
        elif self.right == None and self.left != None:
            return [self.value] + self.left.tree_to_list()
    elif self.right != None:
        return [self.value] + self.right.tree_to_list()
    else:
        return [self.value]
    
def is_tree(self):
    
    if self.left:
        if self.left.value < self.value:
            return self.left.is_tree()
        else:
            return False
    if self.right:
        if self.right.value > self.value:
            return self.right.is_tree()
        else:
            return False
    
    return True

def tree_to_list_iter(self):
    
    st = [self]
    erg = []
    while st != []:
        job = st.pop()
        erg.append(job.value)
        if job.left: 
            if job.right:
                st.append(job.left)
                st.append(job.right)
            else:
                st.append(job.left)
        elif job.right:
            st.append(job.right)
    return erg
t = Node(random.randint(0,100))
for k in l1:
    t.add(k)
print(t.tree_to_list())
print(t.tree_to_list_iter())

I made a Tree class, then added 100 random ints using the invariants for a tree. I wanted a function that would print out all values of the tree, first recursively, by checking if left or right Node exists, and if so, adding it to a list to then return. Then in iterative with a stack st.

l1 is a list of 100 ints that were generated from random.randint(0,1000)

0 Answers
Related