Reputation: 83
The compiler is saying that there is no matching function for stack::push()
or any stack function I have used in the below code.
This code is for an iterative pre-order traversal of a tree.
Here is the code (or PasteBin):
#include <iostream>
#include <stack>
struct Node {
int data;
Node *parent, *left, *right;
} *root = nullptr;
Node *createNode(int num) {
Node *new_node = new Node;
new_node -> data = num;
new_node -> parent = new_node -> left = new_node -> right = nullptr;
return new_node;
}
void createTree(int num) {
Node *new_node = createNode(num);
if(!root) {
root = new_node;
return;
}
Node *head = root, *parent_node = root;
while(head) {
if(num < head -> data) {
if(head -> left == nullptr) {
head -> left = new_node;
new_node -> parent = parent_node;
}
parent_node = head;
head = head -> left;
}
else {
if(head -> right == nullptr) {
head -> right = new_node;
new_node -> parent = parent_node;
}
parent_node = head;
head = head -> right;
}
}
}
void preorderTraversal(Node *head) {
std::stack<Node> s;
while(1) {
while(head) {
s.push(head);
std::cout << head -> data << " ";
head = head -> left;
}
if(!s.empty())
break;
head = s.top();
head = head -> right;
s.pop();
}
}
int main() {
int num;
for(int i = 0; i < 7; i++) {
std::cin >> num;
createTree(num);
}
preorderTraversal(root);
std::cout << std::endl;
return 0;
}
Upvotes: 2
Views: 5000
Reputation: 83
It should be std::stack<Node*> s
in place of std::stack<Node> s
because the stack should contain elements which are pointer to the Node or Node*
.
Sorry, my bad!
Upvotes: 3