how do I assign a name to the left child of the left child of the root? I am new with classes. the last two lines are where I try to make the assignment. Help is appreciated!
class BinaryTree:
def __init__(self,rootName):
self.root = rootName
self.leftChild = None
self.rightChild = None
def insertLeft(self,newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertRight(self,newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getRightChild(self):
return self.rightChild
def getLeftChild(self):
return self.leftChild
def setRootVal(self,obj):
self.root = obj
def getRootVal(self):
return self.root
r = BinaryTree('a')
r.leftChild = 'b'
r.rightChild = 'c'
r.insertLeft = BinaryTree('b')
r.insertRight = BinaryTree('c')
r.getLeftChild().leftChild = 'd'
r.leftChild.leftChild = 'd'
both of the last two statements give me this error: 'str' object has no attribute 'getRootVal' I am trying to create a tree that looks like this: enter image description here
1 Answer 1
Looking at the interface of BinaryTree, you are supposed to call insertLeft and insertRight to add children to the tree, instead of:
r.leftChild = 'b'
r.rightChild = 'c'
leftChild and rightChild are supposed to be BinaryTree objects, not strings. Although you could write:
r.leftChild = BinaryTree('b')
r.rightChild = BinaryTree('c')
It doesn't handle the case when leftChild and rightChild are not None. This is why you should use insertLeft and insertRight, which does handle these cases for you:
r.insertLeft('b')
r.insertRight('c')
To insert d, e and f, we do it the same way using insertLeft and insertRight:
r.getLeftChild().insertRight('d')
r.getRightChild().insertLeft('e')
r.getRightChild().insertRight('f')
BinaryTreeclass. What does the homework require you to do?insertLeftandinsertRightare functions, not attributes. As such you should be doingr.insertLeft('b')andr.insertRight('c'). The code runs after this modification, although I agree with @Sweeper and you could implement this better.