简体   繁体   中英

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

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() 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM