-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathiterative-tree-traversal-1.cpp
More file actions
42 lines (36 loc) · 947 Bytes
/
iterative-tree-traversal-1.cpp
File metadata and controls
42 lines (36 loc) · 947 Bytes
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
#include <bits/stdc++.h>
using namespace std;
struct node{
int val;
node *left, *right;
node(int x) {
val = x;
left = right = NULL;
}
};
unordered_map<node*, int> cnt;
void traversal_trick(node *root) {
//postorder
stack<node*> S;
S.push(root);
while(!S.empty()){
node* cur = S.top();
if(cur == NULL) { S.pop(); continue; }
if (cnt[cur] == 0) S.push(cur->left);
else if (cnt[cur] == 1) S.push(cur->right);
else if (cnt[cur] == 2) cout << cur->val << " " ;
else S.pop();
cnt[cur]++;
}
}
int main()
{
node *root = new node(7);
node *t = root;
root->left = new node(3); root->right = new node(10);
root->left->left = new node(2); root->left->right = new node(5);
root->left->left->left = new node(1);
root->right->left = new node(8);
root->right->right = new node(12);
traversal_trick(root);
}