0

在 C++ 中,如果我有以下形式的二叉搜索树 (BST)

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

像这样访问 leftChild 数据是否合法:

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

此外,有时我看到链表节点对子节点使用 *node,而其他时候他们只使用节点。何时/为什么要使用其中任何一个。对不起,字符串问题只是好奇。

4

1 回答 1

3

不,因为你不能有这样的结构。它将是无限大的(anode有两个孩子node,每个孩子都有两个孩子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 回答