Предполагая, что {id, parent_id}
пары находятся в словаре / карте, вы можете найти максимальную глубину, используя памятка :
Основная функция (псевдокод):
Map tree; // <<=== This is your tree; id is the key; parent_id is the value
Map depth; // This map is used for memoization
int max = -1;
foreach pair in tree
max = Max(memoized_depth(id, tree, depth), max)
Функция рекурсивной глубины:
int memoized_depth(id, tree, depth)
if (depth.containsKey(id)) return depth[id];
if (!tree.contains(id)) return 0; // no parent means it's a root
int res = memoized_depth(tree[id] // parent, tree, depth) + 1;
depth[id] = res;
return res;