0

So I'm using the binary tree class to build trees I'm making simple trees but can't figure out why I keep getting errors

class BinaryTree:

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

def insert_left(self, new_data):
    if self.left == None:
        self.left = BinaryTree(new_data)
    else:
        t = BinaryTree(new_data)
        t.left = self.left
        self.left = t

def insert_right(self, new_data):
    if self.right == None:
        self.right = BinaryTree(new_data)
    else:
        t = BinaryTree(new_data)
        t.right = self.right
        self.right = t

def get_left(self):
    return self.left

def get_right(self):
    return self.right

def set_data(self, data):
    self.data = data

def get_data(self):
    return self.data

I have the code above but can't figure out how to implement it to get a tree like this enter image description here

I've tried running it through def create_a_tree(): tree=BinaryTree('a') tree.insert_left('b') tree.insert_right('c') return(tree)

But this doesn't work

Sharl
  • 175
  • 5
  • 15
  • 1
    Please be more specific about what "doesn't work." Also, your code is not formatted correctly `__init__` and so should the rest of the methods. It is hard to figure out the problem without actually seeing what your code looks like. – skyler Oct 22 '15 at 23:10
  • Have you indented everything correctly? I ran your code through your example and it seems to be working just fine after I fixed indentation. – user3846506 Oct 22 '15 at 23:10

1 Answers1

0

There are a few things that seem slightly off with your code.

One thing is that the code doesn't seem properly indented. Indentation has a syntactic and semantic value in Python, so if you want your methods to be inside the class you must indent as in

class BinaryTree:

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

The second thing I can see is that you're checking for None using ==, whereas the correct way of doing that is if x is None (see here and here for details).

As a side note: Unlike Java, Python doesn't really need getters and setters, as classes and most objects can be modified at runtime. So instead of declaring a method like set_data, you can simply set bt.data=your_data on a BinaryTree object.

Community
  • 1
  • 1