2017-08-18 13 views
0

与えられたノードのレベルを返したいと思います。私はバイナリツリーでこれを行うことができましたが、n-aryツリーではそれを実行する方法がありません。何か案は ?バイナリツリーのN-Ary Tree C++ - ノードのレベルを見つける方法

溶液であった:

「PTR」はレベルが検索されたノードである
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;} 

。ありがとうございました。ここでN分木の構造は以下の通りである:

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

がで 'levelLeft'と' levelRight'計算を交換するだけの場合、このではありませんループ? – Frank

+0

私は試しましたが動作しませんでした... –

+0

試したことをお見せください – Frank

答えて

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

あなたはいつも、ループの1回の反復の後に戻りますので、あなたは今までの最初の2つのつの子ノードを訪問与えられたノード。

あなたは常に配列全体を反復し、見つかった値(存在する場合)を返すべきである:

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

どうすればいいですか?問題は、 "30"ノードの場合でも関数が0を返すということです。 –

+0

私はあなた自身からインスピレーションを得ることができる例で私の答えを編集しました。 – Frank

+0

私はそれを行う場合は、常に "17"と "15"の場合は0を返します。 –

関連する問題