【发布时间】:2015-07-29 16:43:57
【问题描述】:
void addElement(struct BinaryTree *root, int data) {
if (!root)
return;
BinaryTree *newNode = new BinaryTree;
newNode->data = data;
newNode->right = NULL;
newNode->left = NULL;
queue<BinaryTree> *myqueue = new queue<BinaryTree>;
myqueue->push(*root); // Why do i have to dereference the object to store it in the queue;
BinaryTree *temp;
while (!myqueue->empty()) {
temp = myqueue->front()
//Throwing an error
myqueue->pop();
if (temp->left) {
myqueue->push(*temp->left);
} else {
temp->left = newNode;
break;
}
if (temp->right) {
myqueue->push(*temp->right);
} else {
temp->right = newNode;
break;
}
}
}
【问题讨论】:
-
C++ 不是 Java,您不必动态分配所有对象。您的队列对象不必是指针并动态分配,它可能导致指针问题和内存泄漏(您有)。而是将其定义为普通的非指针对象
std::queue<BinaryTree> myqueue; -
至于解引用,与
root的类型相比,考虑一下存储在队列中的类型。此外,这种混淆是代码无法编译的原因。