【问题标题】:Binary tree coding problems with c++? [closed]C++的二叉树编码问题? [关闭]
【发布时间】:2019-12-23 11:02:47
【问题描述】:
// 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 不能指向标记位置上的父节点?

【问题讨论】:

    标签: c++ pointers reference binary-tree


    【解决方案1】:

    您不得重新分配参考。 所以这个说法

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 2015-01-19
      • 2016-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多