I've tried to create an implementation of a tree for comments. I want use it in Django to store comments. Please tell me how to implement it much simpler, without recursion, to find child nodes.
class commentTree(object):
def __init__(self, id, data, parentId = 0, childrens = None):
"Represents one leaf Tree"
self.id = id
self.parentId = parentId
self.title = data['title']
self.body = data['body']
self.childrens = []
self.isLeaf = True if len(self.childrens) > 0 else False
if childrens is not None:
for children in childrens:
self.childrens.append(children)
def addComment(self, parentId, data):
root = 1 if self.isLeaf == False else 0
comment = commentTree(parentId + root + len(self.childrens), data, self.id)
if parentId == self.id:
self.childrens.append(comment)
else:
node = self.findById(parentId)
node.childrens.append(comment)
def getParent(self, node):
"Gets parent node"
if self.parent is not None:
return self.parent
def getSize(self, node):
"Returns size of childrens length + node"
return len(node.childrens) + 1
def findById(self, id):
def searchInChildren(id, childNodes):
for children in childNodes:
if children.id == id:
return children
else:
searchInChildren(id, children)
if id == self.id:
return self
else:
result = searchInChildren(id, self.childrens)
if result.id == id:
return result
else: return None
def getSiblings(self, node):
"Get nodes that have one parent"
nodes = []
def getAllChildrens(self, child):
for children in node.childrens:
nodes.append(children)
if children.isLeaf:
getAllChildrens(self, children)
getAllChildrens(self, node)
return nodes