data structures - N-Ary Tree C++ - How to find the level of a node -
i returns level of given node. i've been able binary trees n-ary trees there no way run it. ideas ?
for binary tree solution was:
int findlevel(binalbero<int>::node root, binalbero<int>::node ptr, int level = 0) { if (root == null) return -1; if (root == ptr) return level; // if null or leaf node if (root->left == null && root->right == null) return -1; // find if ptr present in left or right subtree. int levelleft = findlevel(root->left, ptr, level + 1); int levelright = findlevel(root->right, ptr, level + 1); if (levelleft == -1) return levelright; else return levelleft;} where "ptr" node level searched. thank you. here structure of n-ary tree:
class alberon { public: typedef t tipoelem; typedef bool boolean; struct nodoalbero { tipoelem elemento; struct nodoalbero* parent; /*primo figlio*/ struct nodoalbero* children; struct nodoalbero* brother; }; typedef nodoalbero* node; /*......*/ private: nodo root;}; if use tree:
8 / / \ \ 17 30 18 7 / 15 / \ 51 37 i tried function returns exact level node 17 , 15. code:
int findlevel(alberon<int> t, alberon<int>::nodo root, alberon<int>::nodo ptr, int level = 0) { if (root == ptr) { return level;} if (root == null) return -1; if (!t.leaf(root)) { level++; root = t.firstson(root); findlevel(t, root, ptr, level);} if (!t.lastbrother(root)) { root = t.succbrother(root); findlevel(t, root, ptr, level);} return level;}
int livellofiglio = findlevel(temp, ptr, level + 1); while (temp != null) { temp = t.succbrother(temp); int livellofratello = findlevel(temp, ptr, level + 1); if (livellofiglio == -1) return livellofratello; else return livellofiglio; } you return after single iteration of loop, ever visit first 2 child nodes of given node.
you should iterating on entire array, , return found value (if present):
while (temp != null) { int livellofratello = findlevel(temp, ptr, level + 1); if (livellofratello != -1) return livellofratello; temp = t.succbrother(temp); } return -1
Comments
Post a Comment