我正在实现一个前序遍历功能。但我陷入了 pop() 函数。它不断给出此错误“从不兼容的类型‘void’分配给‘节点*’”。我已经尝试使用 node* 而不是 void 函数,但是这个一直给出错误。
不工作
#include <iostream>
#include <stack>
using namespace std;
class node {
public:
int data;
node *left;
node *right;
node(int d) {
this->data = d;
this->left = NULL;
this->right = NULL;
}
};
void preOrderTraversalR(node *root) {
if (root) {
cout << root->data << " ";
preOrderTraversalR(root->left);
preOrderTraversalR(root->right);
}
}
node* preOrderTraversalS(node *root){
stack<node*> S;
while(1){
while(root){
cout<<root->data;
S.push(root);
root = root->left;
}
if(S.empty()) break;
root = S.pop();
root=root->right;
}
}
node *createTree(node *root) {
int val;
cout << "Enter Node: ";
cin >> val;
root = new node(val);
if (val == -1) {
return NULL;
}
cout << "Enter node left of " << val << " : ";
root->left = createTree(root->left);
cout << "Enter node right of " << val << " : ";
root->right = createTree(root->right);
return root;
}
// 8 3 1 -1 -1 6 4 -1 -1 7 -1 -1 10 -1 14 13 -1 -1
int main() {
node *root = NULL;
root = createTree(root);
cout << "\n";
preOrderTraversalR(root);
}
您遇到的错误是因为您错误地使用了
S.pop()
(至少,我认为是这样。如果这是有意的,请纠正我)。 C++ 中堆栈容器的 pop()
方法不会返回弹出的元素,它只是从堆栈中删除顶部元素。要解决此问题,您应该将 S.pop()
更改为 S.top()
以访问堆栈的顶部元素,然后使用 S.pop()
将其删除。
否则,您只需从堆栈中删除顶部元素并将
void
值分配给 root
指针即可。 (这就是这里发生的事情)
node* preOrderTraversalS(node *root){
stack<node*> S;
while(1){
while(root){
cout << root->data << " ";
S.push(root);
root = root->left;
}
if(S.empty()) break;
root = S.top(); // Access the top element of the stack
S.pop(); // Remove the top element from the stack
root = root->right;
}
return nullptr; // You should also return something here, perhaps nullptr
}
希望有帮助。
还有,好像可能是输入机制有问题,导致节点输入不定提示。如果您需要任何帮助或进一步说明,请随时与我们联系。