0

I would like to returns the level of a given node. I've been able to do this for binary trees but for n-ary trees there is no way to run it. Any ideas ?

For the binary tree the 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 is present in the 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" is the node for which the level is searched. Thank you. Here is the 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 i use this tree:

          8
      /  /  \  \ 
     17 30  18  7
     /
    15

  /  \
 51  37

I tried but the function returns the exact level only for node 17 and 15. With this 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;}
Antonio M
  • 1
  • 2

1 Answers1

0
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 will always return after a single iteration of your loop, so you only ever visit the first two child nodes of a given node.

You should always be iterating over the entire array, and return the 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
  • How can i do it ? The problem is that, also for the "30" node the function return 0. – Antonio M Aug 18 '17 at 16:28
  • I've edited my answer with an example you can inspire yourself from. –  Aug 18 '17 at 16:30
  • If i do that, return always 0 ... also for the "17" and "15" . – Antonio M Aug 18 '17 at 16:32
  • I edited the post ... I tried this way and the function can find the exact node with "if(root == ptr)" and also cycles on all tree nodes. However, when there is "return level" in the if() statement, it return the value but doesn't return it at th end of the function . Solutions ? – Antonio M Aug 19 '17 at 07:45