不,因为你不能有这样的结构。它将是无限大的(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!
}