C ++的二叉树编码问题?
Binary tree coding problems with c++?
// Node
struct Node
{
int val;
string color;
Node* left_child;
Node* right_child;
};
为什么下面的代码不起作用?
Node* node = new Node();
Node* &test_node = node->left_child;
test_node = new Node();
test_node->val = 1;
test_node = test_node->left_child; // this
test_node = new Node();
test_node->val = 2;
为什么test_node不能指向标记位置的父节点?
您不能重新分配参考。
所以这个声明
test_node = test_node->left_child;
只是用 NULL
覆盖 node->left_child
的先前值。
使用指针代替引用。例如
Node **test_node = &node->left_child;
*test_node = new Node();
( *test_node )->val = 1;
test_node = &( *test_node )->left_child;
*test_node = new Node();
( *test_node )->val = 2;
// Node
struct Node
{
int val;
string color;
Node* left_child;
Node* right_child;
};
为什么下面的代码不起作用?
Node* node = new Node();
Node* &test_node = node->left_child;
test_node = new Node();
test_node->val = 1;
test_node = test_node->left_child; // this
test_node = new Node();
test_node->val = 2;
为什么test_node不能指向标记位置的父节点?
您不能重新分配参考。 所以这个声明
test_node = test_node->left_child;
只是用 NULL
覆盖 node->left_child
的先前值。
使用指针代替引用。例如
Node **test_node = &node->left_child;
*test_node = new Node();
( *test_node )->val = 1;
test_node = &( *test_node )->left_child;
*test_node = new Node();
( *test_node )->val = 2;