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

时间:2017-08-18 15:57:37

标签: c++ data-structures tree binary-tree n-ary-tree

我想返回给定节点的级别。我已经能够为二叉树做到这一点,但对于n-ary树,没有办法运行它。有什么想法吗?

对于二叉树,解决方案是:

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

其中“ptr”是搜索级别的节点。谢谢。这是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;};

如果我使用这棵树:

          8
      /  /  \  \ 
     17 30  18  7
     /
    15

  /  \
 51  37

我尝试了但该函数仅返回节点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;}

1 个答案:

答案 0 :(得分: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;
}

在循环的单次迭代后,您将始终返回,因此您只能访问给定节点的前两个子节点。

您应始终迭代整个数组,并返回找到的值(如果存在):

while (temp != NULL) {
  int livellofratello = findLevel(temp, ptr, level + 1);
  if (livellofratello != -1)
    return livellofratello;
  temp = t.succBrother(temp);
}
return -1