Skip to content

Commit a062403

Browse files
committed
add code iterative inorder traversal
1 parent 0c4c5d1 commit a062403

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

a.out

248 Bytes
Binary file not shown.

iterative-inorder-traversal.cpp

+34
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,38 @@ void inorder(Node *root){
3434
if(!root && s.empty())
3535
break;
3636
}
37+
cout << endl;
38+
}
39+
40+
void preorder(Node *root){
41+
stack<Node *> s;
42+
s.push(root);
43+
while(!s.empty()){
44+
Node *temp = s.top();
45+
s.pop();
46+
cout << temp->data << " ";
47+
if(temp->right) s.push(temp->right);
48+
if(temp->left) s.push(temp->left);
49+
}
50+
cout << endl;
51+
}
52+
53+
void postorder(Node *root){
54+
stack<Node*> s1,s2;
55+
s1.push(root);
56+
while(!s1.empty()){
57+
Node *temp = s1.top();
58+
s1.pop();
59+
s2.push(temp);
60+
if(temp->left) s1.push(temp->left);
61+
if(temp->right) s1.push(temp->right);
62+
}
63+
while(!s2.empty()){
64+
Node *temp = s2.top();
65+
s2.pop();
66+
cout << temp->data << " ";
67+
}
68+
cout << endl;
3769
}
3870

3971
int main(){
@@ -43,5 +75,7 @@ int main(){
4375
root->left->left = getNode(4);
4476
root->left->right = getNode(5);
4577
inorder(root);
78+
preorder(root);
79+
postorder(root);
4680
return 0;
4781
}

0 commit comments

Comments
 (0)