C++ 为什么我的一个打印函数正在删除节点?
好的,我的二叉树程序有一个打印函数,它以宽度优先打印所有内容。当我调用它时,它会按我期望的顺序打印,但是它也会删除除一个节点之外的所有节点,并给我留下一个空树C++ 为什么我的一个打印函数正在删除节点?,c++,binary-tree,C++,Binary Tree,好的,我的二叉树程序有一个打印函数,它以宽度优先打印所有内容。当我调用它时,它会按我期望的顺序打印,但是它也会删除除一个节点之外的所有节点,并给我留下一个空树 void BST::breadth(Node *& cur_root) { if (cur_root != NULL) { cout << cur_root->m_value; if (cur_root->m_left != NULL) {
void BST::breadth(Node *& cur_root)
{
if (cur_root != NULL) {
cout << cur_root->m_value;
if (cur_root->m_left != NULL) {
myqueue.push(cur_root->m_left);
}
if (cur_root->m_right != NULL) {
myqueue.push(cur_root->m_right);
}
if (!myqueue.empty()) {
cout << ", ";
cur_root = myqueue.front();
myqueue.pop();
breadth(cur_root);
} else {
cout << "}" << endl;
}
}
}
void BST::宽度(节点*&cur\u根)
{
if(cur_root!=NULL){
库姆值;
如果(cur_root->m_left!=NULL){
myqueue.push(cur\u root->m\u left);
}
if(cur_root->m_right!=NULL){
推送(cur\u root->m\u right);
}
如果(!myqueue.empty()){
库特
接受对指针的引用
cur_root = myqueue.front();
将其更改为子节点之一。您只需重写它
接受对指针的引用
cur_root = myqueue.front();
将其更改为子节点之一。您只需重写它。因为您通过引用而不是通过值传递cur\u root
。当width
函数返回时,您的cur\u root
指向其他对象(树的末尾)
您还可以避免递归:
void BST::breadth(Node* root)
{
std::queue<Node*> myqueue;
myqueue.push_back(root);
bool first = true;
cout << "{";
while (myqueue.empty() == false) {
cout << (first ? "" : ",");
first = false;
Node* current = myqueue.front();
myqueue.pop();
cout << current->m_value;
if (current->left) {
myqueue.push(current->left);
}
if (current->right) {
myqueue.push(current->right);
}
}
cout << "}" << endl;
}
void BST::宽度(节点*根)
{
std::queue myqueue;
myqueue.push_back(根);
bool first=true;
不能离开);
}
如果(当前->右侧){
myqueue.push(当前->右侧);
}
}
cout因为您是通过引用而不是通过值传递cur\u root
。当width
函数返回时,您的cur\u root
指向其他对象(树的末尾)
您还可以避免递归:
void BST::breadth(Node* root)
{
std::queue<Node*> myqueue;
myqueue.push_back(root);
bool first = true;
cout << "{";
while (myqueue.empty() == false) {
cout << (first ? "" : ",");
first = false;
Node* current = myqueue.front();
myqueue.pop();
cout << current->m_value;
if (current->left) {
myqueue.push(current->left);
}
if (current->right) {
myqueue.push(current->right);
}
}
cout << "}" << endl;
}
void BST::宽度(节点*根)
{
std::queue myqueue;
myqueue.push_back(根);
bool first=true;
不能离开);
}
如果(当前->右侧){
myqueue.push(当前->右侧);
}
}
因为myqueue.pop();
或者因为您重新分配了cur\u root=myqueue.front();
?第二个代码块中返回的size()
是什么?如果由于myqueue.pop();
或者因为您重新分配了cur\u root=myqueue.front(),为什么要通过引用传递指针;
?什么是尺寸()
返回您的第二个代码块?如果只是为了打印值,为什么要通过引用传递指针?天啊,在我要求之前,我已经把头发撕了好几个小时,就在我发布之前,我意识到这可能是个问题。您是对的,谢谢!哦,我的天啊,在我要求之前,就在我发布之前,我已经把头发撕了好几个小时了我意识到这可能是问题所在。你是对的,谢谢!