1

I'm creating a Binary Search Tree and I want to implement inorder traversal using recursion for which I need to pass in root value which in this case is self.root.

class BST:
    def __init__(self):
        self.root = None

    def inOrder(self, root):
        if root == None:
            return
        self.inOrder(root.left)
        print(root.data, end=" ")
        self.inOrder(root.right)

How do I pass root's default value to be equal to self.root? If I use:

class BST:
    def __init__(self):
        self.root = None

    def inOrder(self, root = self.root):
        if root == None:
            return
        self.inOrder(root.left)
        print(root.data, end=" ")
        self.inOrder(root.right)

It shows error that self is not defined.

martineau
  • 119,623
  • 25
  • 170
  • 301
Ayush
  • 31
  • 5

1 Answers1

2

Even if this were possible, it would not be a good idea. The objects used as default arguments are set when the code is first interpreted, not each time the method is called. That means self.root must exist when the code is first interpreted, and every time the default argument is used, it would be referencing the original self.root object; not whatever self.root happened to be when the method was called. It is for this reason that you should really never have a mutable object as a default argument. Multiple calls to a functions all using the same mutable default argument leads to wonky, erroneous behavior.

The typical workaround option is to default to None, then check on that:

def inOrder(self, root=None):
    if root is None:
        root = self.root
    . . .

Unfortunately, that won't work here because None has a special meaning in your function. You could instead use a sentinel object:

sentinel = object()  # A unique object

. . .

def inOrder(self, root=sentinel):
    if root is sentinel: 
        root = self.root
    . . .

Or, you could alter your program so that None is not a valid argument into that method, then use None instead of sentinel.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117