0

I have just started learning python and I am trying to write a binary search tree. Eclipse does not show any errors but when I try to run there is ann error

Encountered "self" at line 5

Line 5 is:

"self.left = left"

What is the problem? Is my way of writing code okey? I have just starded python.

class Node:

    def _init_(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right 

    def add_node(self, data):
        if self.data is None:
            node = Node(data)
            self = node
        if self.data > data:
            self.add_node(self.left, data)
        else:
            self.add_node(self.right, data)

    def print_nodes(self):
        if self.left is not None:
            self.print_nodes(self.left)
        print(self);
        if self.right is not None:
            self.print_nodes(self.right)

    def _str_(self):
        print(self.data)

class binary_tree:

    def _init_(self):
        self.root = None

    def getRoot(self):
        return self.root

    def add(self, data):
        self.root.add_node(data)

    def print_all(self):
        self.root.print_nodes();
fjarri
  • 9,546
  • 39
  • 49
Mateusz
  • 604
  • 8
  • 20
  • Are you sure that's the exact code you are executing? I do not see any syntax errors. Incidentally, you probably want to write `__init__` and `__str__` instead of `_init_` and `_str_`. – fjarri Jan 29 '16 at 00:00
  • 3
    One thing: Maybe you want `__init__` instead of `_init_`. See also [this question](http://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do). – e0k Jan 29 '16 at 00:00
  • ok, changed but still the same error – Mateusz Jan 29 '16 at 00:02
  • please provide the complete traceback ... – Joran Beasley Jan 29 '16 at 00:02
  • I am using eclipse and all I see is this error on left down size in red font colour. Console does not show anything – Mateusz Jan 29 '16 at 00:05
  • When I run "python3 binarytree.py " in console then it does nothing – Mateusz Jan 29 '16 at 00:08
  • Did you try creating any objects of the classes you defined? – TigerhawkT3 Jan 29 '16 at 00:14
  • Of course it does nothing - at least nothing you can see. Your code defines two classes and that's all. Why do you think something should happen? – Matthias Jan 29 '16 at 00:17
  • I think eclipse does not know it is supposed to use python or something ... maybe try using idle or something easier for now ... I think eclipse may be confusing you – Joran Beasley Jan 29 '16 at 00:17
  • Yeah, I would avoid using Eclipse. Probably not time for you to jump into vim, but any other edit will probably serve you better than Eclipse for Python development. I highly recommend learning nano/emacs/vim at some point however. – Alex Alifimoff Jan 29 '16 at 00:19
  • Ok, so how to fix it to be able to run it and create example tree object? – Mateusz Jan 29 '16 at 11:40

2 Answers2

1

here a few fix to your code

class Node:

    def __init__(self, data, left=None, right=None):
        self.data  = data
        self.left  = left
        self.right = right 

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

    def print_nodes(self):
        if self.left is not None:
            self.left.print_nodes()
        print(self);
        if self.right is not None:
            self.right.print_nodes()

    def __str__(self):
        return str(self.data)

class binary_tree:

    def __init__(self):
        self.root = None

    def getRoot(self):
        return self.root

    def add(self, data):
        if self.root is None:
            self.root = Node(data)
        else:
            self.root.add_node(data)

    def print_all(self):
        if self.root is None:
            print("Empty tree")
        else:
            self.root.print_nodes()

as mention before the special method of python are __init__ and __str__, all magic method start and end with a __.

I fix your add_node because your recursive call were wrong, went you do self.add_node(self.left,data) the self instance is implicitly pass as the first argument to that function, self.left is the second and data the third but as defined add_node only take 2 argument so that is a error, so in this case if you want to call the add_node of self.left that is done by self.left.add_node and the same apply to every other call to a method of a class

take a look at:

a first look at classes

basic customization and magic methods

here sample usage of this tree

>>> tree = binary_tree()
>>> tree.print_all()
Empty tree
>>> tree.add(23)
>>> tree.print_all()
23
>>> tree.add(10)
>>> tree.add(42)
>>> tree.print_all()
10
23
42
>>> root = tree.root
>>> root.data
23
>>> root.right
<__main__.Node object at 0x0000000003559160>
>>> root.right.data
42
>>> root.left
<__main__.Node object at 0x0000000003577080>
>>> root.left.data
10
>>>     

Other thing is that in python you dot need to define getter or setter unless you want to control what and how a attribute is set or return it in a especial way that is different to the actual object.

run this in the IDLE of python or in interactive mode as python3 -i binarytree.py or in your favorite interprete of python.

Copperfield
  • 8,131
  • 3
  • 23
  • 29
1

#What you want is for the user to just access these functions by providing some data values so you can not traverse through the tree as self is itself and along with self you are just passing the data as a positional argument so for that you need a helper function along with it that takes two arguments root and data and then you call that helper function in main function

`The code starts from class Binary tree

class BinaryTree: def init(self,data): self.data=data self.left=None self.right=None import queue class BST: def init(self): self.root=None self.numnodes=0

def printtreehelper(self,root):
    
    q=queue.Queue()
    if root==None:
        return 
    q.put(root)
    while(not(q.empty())):
        curr_node=q.get()
        print(curr_node.data,end=':')

        if curr_node.left!=None:
            q.put(curr_node.left)
            print("L",curr_node.left.data,end=",")
        else:
            print("L",-1,end=",")

        if curr_node.right!=None:
            q.put(curr_node.right)
            print("R",curr_node.right.data,end=" ")
        else:
            print("R",-1,end="")
        print()

def printtree(self):
    return self.printtreehelper(self.root)

def ispresenthelper(self,root,data):
    if root==None:
        return False
    if root.data==data:
        return True
    if root.data>data:
         return self.ispresenthelper(root.left,data)
    else:
        return self.ispresenthelper(root.right,data)

def ispresent(self,data):
    return self.ispresenthelper(self.root,data)


def inserthelper(self,root,data):
    if root==None:
        node=BinaryTree(data)
        return node
    if root.data>data:
        root.left=self.inserthelper(root.left,data)
        return root
    if root.data<data:
        root.right=self.inserthelper(root.right,data)
        return root

def insert(self,data):
    self.numnodes+=1
    self.root=self.inserthelper(self.root,data)

def mini(self,root):
    if root==None:
        return 100000
    if root.left==None:
        return root.data
    return self.mini(root.left)
    
def deletehelper(self,root,data):
    if root==None:
        return False,None
    
    if root.data>data:
        deleted,newleftnode=self.deletehelper(root.left,data)
        root.left=newleftnode
        return deleted,root
    if root.data<data:
        deleted,newrightnode=self.deletehelper(root.right,data)
        root.right=newrightnode
        return deleted,root
    
    if root.data==data:
        #leafNode
        if root.left==None and root.right==None:
            return True,None
        #if one child
        if root.left==None:
            return True,root.right
        if root.right==None:
            return True,root.left
        #if both child
        replacement=self.mini(root.right)
        root.data=replacement
        deleted,newrightnode=self.deletehelper(root.right,replacement)
        root.right=newrightnode
        return deleted,root
    
def delete(self,data):
    deleted,newroot=self.deletehelper(self.root,data)
    if deleted:
        self.numnodes-=1
    self.root=newroot
    return deleted

def count(self):
    return self.numnodes`