I have created a class with Node:
class Node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
And fill the tree with some data, I want depth of a tree without recursion:
def depth(self, data):
self.depth = dict()
root = self.dict[self.root] # this works, I got the root, it is declared in another init
if root.data == data:
return 0
q = set()
q.add(0)
q.add(root)
while q:
element = q.pop()
if type(element) == int:
if q == set():
break
else:
key = element
q.add(element+1)
else:
v = element
try:
self.depth[v.data].add(key)
except KeyError:
self.depth[v.data] = key
if v.right is not None:
q.add(v.right)
if v.left is not None:
q.add(v.left)
if data == v.data:
break
return self.depth[data]
This code should return the depth of element data. It works with lists, but I have timeout with them so I must use set instead. With sets it gets wrong results. (For example 19 instead of 6)
q? You put different types of things in it, namely numbers andNodes.