0

C ++では、次の形式のバイナリ検索ツリー(BST)がある場合

Struct node{ 
 node leftChild; 
 node rightChild; 
 int data;}

次のようにleftChildデータにアクセスすることは合法ですか?

foo (node head)
    {
    std::cout << head.leftChild.data; 
    }

また、リンクリストノードが子に* nodeを使用している場合もあれば、単にnodeを使用している場合もあります。いつ/なぜどちらかを使用しますか。文字列の質問が気になるのでごめんなさい。

4

1 に答える 1

3

いいえ、そのような構造を持つことはできないからです。それは無限に大きくなります(anodeには2つの子nodeがあり、それぞれに2つの子がありますnode。など)。これが、同じタイプの子を持つノードを作成するときに人々がポインターを使用する理由です。

たとえば、それを行わない方法:

/* This is a problem because of the recursive nature of the structure. leftChild also
contains a leftChild itself, which also contains a leftChild, etc. forever. */
struct node
{ 
    node leftChild; // how big is leftChild? infinitely large!
    node rightChild; // how big is rightChild? infinitely large!
    int data;
}

そしてそれを行う正しい方法:

/* This is not a problem because the size of a pointer is always 4 bytes (assuming 32-
bit system). You can allocate room for the child nodes without recursively requiring an
infinite amount of memory. */
struct node
{ 
    node* leftChild; // how big is leftChild? 4 bytes (assuming 32-bit system)
    node* rightChild; // how big is rightChild? 4 bytes (assuming 32-bit system)
    int data;
}

あなたがそれを正しい方法でやったら、言うことは完全に合法です:

void foo(node head)
{
    std::cout << head.leftChild->data; // assuming leftChild points to a valid object!
}
于 2012-09-25T05:11:27.423 に答える