-
Notifications
You must be signed in to change notification settings - Fork 72
/
Inorder_Iterative_Stack.cpp
69 lines (65 loc) · 1.5 KB
/
Inorder_Iterative_Stack.cpp
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <complex>
#include <math.h>
#include <utility>
#include <cmath>
#include <set>
#include <vector>
#include <map>
#include <cctype>
#include <queue>
#include <stdio.h>
#include <cstdio>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <numeric>
#include <memory.h>
#define all(a) (a).begin(),(a).end()
#define gcd __gcd
#define bitcount __builtin_popcount
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<int> inorderTraversal(TreeNode* root) {
vector<int> nodes;
stack<TreeNode*> todo;
while (root || !todo.empty()) {
while (root) {
todo.push(root);
root = root -> left;
}
root = todo.top();
todo.pop();
nodes.push_back(root -> val);
root = root -> right;
}
return nodes;
}
int main() {
TreeNode* root = new TreeNode(5);
TreeNode* nd1 = new TreeNode(6);
TreeNode* nd2 = new TreeNode(3);
root -> left = nd2;
root -> right = nd1;
TreeNode* nd3 = new TreeNode(2);
TreeNode* nd4 = new TreeNode(4);
nd2 -> left = nd3;
nd2 -> right = nd4;
TreeNode* nd5 = new TreeNode(1);
nd3 -> left = nd5;
vector<int> in = inorderTraversal(root);
cout << "Inorder traversal: ";
for(int i = 0; i < in.size(); i++) {
cout << in[i] << " ";
}
return 0;
}