0

How would I set the default parent node to root in this binary tree in Python?

I have the following, but its giving the error below.

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

  def insertNode(self,parentNode=self.root,node=None):
    if self.root is None:
      self.root=node

This is the error its giving:

    def insertNode(self,parentNode=self.root,node=None):
NameError: name 'self' is not defined

Thanks in advance

Tom Franks
  • 41
  • 1
  • 1
  • 3

1 Answers1

0

The self.root cannot be evaluated as argument. A simple way to do it is :

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

  def insertNode(self,parentNode=None,node=None):
    if parentNode is None:
      parentNode=self.root
    if self.root is None:
      self.root=node

But anyway, this is going very bad for a binary tree. Just make a draw on paper of your tree to see how to define methods or maybe you should train on a simplier case about class/object in python.

Vince
  • 336
  • 1
  • 11