私は初心者でCバイナリ検索ツリーで作業しています。ツリーの葉の数を返すメソッドを実行しようとしています。親)子(左/右)HERESに私のツリー構造体がありません:それは、このように作成されCのバイナリ検索ツリーの葉の数
struct Node {
int value;
struct Node *left;
struct Node *right;
};
typedef struct Node TNode;
typedef struct Node *binary_tree;
:
binary_tree NewBinaryTree(int value_root) {
binary_tree newRoot = malloc(sizeof(TNode));
if (newRoot) {
newRoot->value = value_root;
newRoot->left = NULL;
newRoot->right = NULL;
}
return newRoot;
}
私が好きそれに要素を追加します。
void Insert(binary_tree *tree, int val) {
if (*tree == NULL) {
*tree = (binary_tree)malloc(sizeof(TNode));
(*tree)->value = val;
(*tree)->left = NULL;
(*tree)->right = NULL;
} else {
if (val < (*tree)->value) {
Insert(&(*tree)->left, val);
} else {
Insert(&(*tree)->right, val);
}
}
}
を葉の数をカウントする
私の実際の方法:もちろん
int nbleaves(binary_tree tree)
{
int nb;
if(tree->right==NULL && tree->left ==NULL){
nb=nb+1;
}
printf("%d",nb);
}
このdoesntの作業は最初の実際のループをtheresのは、しかし、私はそれを試してみました、それはに要素2222および3を追加した後にエラーが、0(EXを返すdoesntのツリーこの関数は0を返す)。私はこの関数を行う方法を知らない。
ありがとうございました!
、 '置き換えるのprintf( "%d個"、NB);'他{場合と '(!TREE->右= NULL)NB + = nbleaves(ツリー→右)。 if(tree-> left!= NULL)nb + = nbleaves(ツリー→左); }返信nb; ' – ikegami
@ikegami私はこれを試してコンパイルしましたが、そのコードでその関数を呼び出すと、プログラムがクラッシュします –