Reputation: 330
I have the following code:
from typing import Optional
class Tree:
class Tree:
def __init__(self):
self.root: Optional[Node] = None
def __str__(self) -> str:
return f"{self.root.data}"
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
I have this class. I am trying to find maximum data element in my tree. The algorithm I created keeps a temporary element and updates the temporary element if it finds a value greater than this element. At first, I make my temporary element value 0 and then do the following:
if tree.data > temp:
temp = tree.data
but I get the following error:
TypeError: '>' not supported between instances of 'Node' and 'Node'
How can I use the ">" operator in this situation?
Upvotes: 1
Views: 320
Reputation: 19243
Give an implementation of the __gt__
dunder method for the Node
object. This tells Python what basis to compare Node
objects on:
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __gt__(self, other):
return self.data > other.data
Upvotes: 2