c++ - 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;
}
解决方案
推荐阅读
- python - 通过 CMD 使用“Shell: send to”将文件作为参数传递给 python 脚本
- c# - Xamarin Android:获取位于内存中的所有进程
- c++ - 为什么左值引用和右值引用在左值引用中崩溃?
- python-3.x - 更改背景颜色时打开新的 Tk 窗口
- javascript - 如何修复未处理的承诺拒绝警告,强制转换为 objectid 失败
- python - mongo 模型字段在查询字符串和 GraphiQL 查询中不可用
- javascript - 无法在 Chrome 中使用 Javascript 单击要在 Selenium 中使用的按钮
- symfony - Symfony VichUploaderBundle 在控制器中的 DownloadHandler 上自动装配
- java - 在使用 Files.walk API 的 java8 中,无法使用绝对路径从文件夹中读取文件
- python - 有没有办法在 Python 中定义一个作为函数内部参数的变量?