-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.cpp
More file actions
51 lines (45 loc) · 1.22 KB
/
Stack.cpp
File metadata and controls
51 lines (45 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "Stack.h"
#include <iostream>
void Stack::pushNode(tree::Node* node) {
Stack::nodeStack.push(node);
}
void Stack::iterativeInorder(tree::Node* node) {
tree::Node* currentNode = node;
while (currentNode || !nodeStack.empty()) {
while (currentNode) {
pushNode(currentNode);
currentNode = currentNode->left;
}
currentNode = nodeStack.top();
nodeStack.pop();
std::cout << currentNode->value << " ";
currentNode = currentNode->right;
}
}
void Stack::iterativePreorder(tree::Node* node) {
tree::Node* currentNode = node;
pushNode(currentNode);
while (!nodeStack.empty()) {
currentNode = nodeStack.top();
nodeStack.pop();
std::cout << currentNode->value << " ";
if (currentNode->right)pushNode(currentNode->right);
if (currentNode->left)pushNode(currentNode->left);
}
}
void Stack::iterativePostorder(tree::Node* node) {
if (!node) return;
std::stack<tree::Node*> stack1, stack2;
stack1.push(node);
while (!stack1.empty()) {
tree::Node* current = stack1.top();
stack1.pop();
stack2.push(current);
if (current->left) stack1.push(current->left);
if (current->right) stack1.push(current->right);
}
while (!stack2.empty()) {
std::cout << stack2.top()->value << " ";
stack2.pop();
}
}