- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path9IterativePreOrderTraversal.cpp
More file actions
Latest commit
54 lines (46 loc) · 1.3 KB
/
Copy path9IterativePreOrderTraversal.cpp
File metadata and controls
54 lines (46 loc) · 1.3 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
52
53
54
#include<bits/stdc++.h>
usingnamespacestd;
structTreeNode
{
int data;
structTreeNode* left;
structTreeNode* right;
TreeNode(int val)
{
data = val;
left = NULL;
right = NULL;
}
};
vector<int> iterativePreOrderTraversalUsingStack(TreeNode* root){
vector<int>ans;
if(root==NULL) return ans;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode* node = st.top();
st.pop();
if(node->right) st.push(node->right);
if(node->left) st.push(node->left);
ans.push_back(node->data);
}
}
intmain(){
structTreeNode* root = newTreeNode(2);
root->left = newTreeNode(5);
root->left->left = newTreeNode(4);
root->left->left->left = newTreeNode(3);
root->left->left->right = newTreeNode(2);
root->left->right = newTreeNode(5);
root->right = newTreeNode(7);
root->right->left = newTreeNode(9);
root->right->left->right = newTreeNode(2);
root->right->left->right->right = newTreeNode(4);
root->right->left->right->left = newTreeNode(1);
root->right->left->left = newTreeNode(3);
root->right->right = newTreeNode(7);
vector<int> res = iterativePreOrderTraversalUsingStack(root);
for(auto val: res){
cout<<val<<endl;
}
}