简体   繁体   English

N-Ary Tree C ++-如何查找节点的级别

[英]N-Ary Tree C++ - How to find the level of a node

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. 我已经能够对二叉树执行此操作,但对于n元树则无法运行它。 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. 其中“ ptr”是要搜索其级别的节点。 Thank you. 谢谢。 Here is the structure of N-Ary Tree: 这是N-Ary树的结构:

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: 我尝试过,但是该函数仅返回节点17和15的确切级别。使用以下代码:

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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM