1 void NonRecursive_PostOrderTraversal(TreeNode *root){
2 if(!root){
3 cout<<"Empty tree"<<'\n';
4 return;
5 }
6 stack<TreeNode *> s;
7 TreeNode *cur = root;
8 TreeNode *prev = root;
9 s.push(root);
10 while(!s.empty()){
11 if(cur->Left && prev != cur->Left && prev != cur->Right){
12 s.push(cur->Left);
13 prev = cur;
14 cur = cur->Left;
15 continue; //如果有左子树且从未访问过,先访问左子树
16 }
17 if(cur->Right && prev !=cur->Right){
18 s.push(cur->Right);
19 prev = cur;
20 cur = cur->Right;
21 }else{
22 cout<<cur->Value<<", ";
23 prev = cur;
24 s.pop();
25 if(!s.empty()){
26 cur = s.top();
27 }
28 }
29 }
30 cout<<"end"<<'\n';
31 }
2 if(!root){
3 cout<<"Empty tree"<<'\n';
4 return;
5 }
6 stack<TreeNode *> s;
7 TreeNode *cur = root;
8 TreeNode *prev = root;
9 s.push(root);
10 while(!s.empty()){
11 if(cur->Left && prev != cur->Left && prev != cur->Right){
12 s.push(cur->Left);
13 prev = cur;
14 cur = cur->Left;
15 continue; //如果有左子树且从未访问过,先访问左子树
16 }
17 if(cur->Right && prev !=cur->Right){
18 s.push(cur->Right);
19 prev = cur;
20 cur = cur->Right;
21 }else{
22 cout<<cur->Value<<", ";
23 prev = cur;
24 s.pop();
25 if(!s.empty()){
26 cur = s.top();
27 }
28 }
29 }
30 cout<<"end"<<'\n';
31 }