首页 > 解决方案 > c++ - 这会导致任何问题吗?使用将自身作为参数传递的函数分配 var(我很难解释)

问题描述


所以很难解释,所以我就给你看。我正在尝试在 C++ 中实现红黑树。以下是与问题相关的代码(此链接上的完整代码)

我是新手,所以如果我没有使用正确的术语,请原谅我。

我的问题是关于创建根节点。当使用 addValue 添加新值时,它将新节点分配给根,但同时将根作为参数传入。我没有收到任何错误,但感觉这不是一个好方法。

enum colour {RED, BLACK, DOUBLEBLACK};

struct Node{
    int data;
    int colour;
    Node *left, *right, *parent;
    explicit Node(int);
};

class Tree{

    public:
        Tree();
        virtual ~Tree(){};
        void addValue(int);
        Node* insertNode(Node *, Node*);

    private:
        Node* root;

};

Node::Node(int data) {
  this->data = data;
  colour = RED;
  left = right = parent = nullptr;
}

Tree::Tree() {
  root = nullptr;
}

void Tree::addValue(int n) {
  Node *node = new Node(n);
  root = insertNode(root, node);    //*********** this line here
  insertFix(node);
}

Node* Tree::insertNode(Node* root, Node* node) {
  if (root == nullptr)
    return node;

  if(node->data < root->data) {
    root->left = insertNode(root->left, node);
    root->left->parent = root;
  } else if (node->data > root->data) {
    root->right = insertNode(root->right, node);
    root->right->parent = root;
  }
  return root;
}

标签: c++

解决方案


推荐阅读