Home > Mobile >  Can someone explain how the "printtree" function in this python code works
Can someone explain how the "printtree" function in this python code works

Time:04-14

I was trying to figure out how to make a binary tree in python and found this code online. Can anyone explain how the printtree function is able to print out all the values

class node: 

    def __init__(self, data):
        self.leftval = None
        self.data = data 
        self.rightval = None 

    def insert(self, data):
        if self.data == None:
            self.data = data 
        else:
            if data < self.data:
                if self.leftval == None:
                    self.leftval = node(data) 
                else:
                    self.leftval.insert(data)
            elif data > self.data:
                if self.rightval == None:
                    self.rightval = node(data)
                else:
                    self.rightval.insert(data)

    def printtree(self):
        if self.leftval:
            self.leftval.printtree()
        print (self.data)
        if self.rightval:
            self.rightval.printtree()
       

root = int(input("Enter the root value"))
root = node(root)

for i in range (0, 10):
    num = int(input("Enter a number"))
    root.insert(num)

root.printtree() 

CodePudding user response:

This function is based on in-order binary tree traversal. You can read more about tree traversal methods here: Tree_traversal In-order, LNR

  • Related