0

It's not my code but I really want to understand the different kinds of methods used on BST, but have come into a problem and don't understand what this statement does;

class Node:

    def __init__(self, data):

        self.left = None
        self.right = None
        self.data = data

    def insert(self, data):
        if self.data:
            if data < self.data:
                if self.left is None:
                    self.left = Node(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Node(data)
                else:
                    self.right.insert(data)
        else:
            self.data = data

    def PrintTree(self):
        if self.left:
            self.left.PrintTree()
        print(self.data),
        if self.right:
            self.right.PrintTree()

It's simple and I understand the basics, but it's this part here where I get lost:

def PrintTree(self):
        if self.left:
            self.left.PrintTree()
        print(self.data),
        if self.right:
            self.right.PrintTree()

Can anybody explain this to me?

  • It's short for `if self.left is not None:` in this context. – Barmar Oct 14 '20 at 15:16
  • `if self.left:`, when `left` is guaranteed to be either `None` or a `Node` object, is basically equivalent to `if self.left is not None:`. – Charles Duffy Oct 14 '20 at 15:17
  • It's an `inorder traversal`. If the left subtree of the current node is not None, then traverse it. Then print the data in the current node. Then, if the right subtree of the current node is not None, traverse it. – Mario Camilleri Oct 14 '20 at 15:19

0 Answers0