后序遍历需要借助一个pre指针来判定之前走过的路径。
后序遍历过程中节点可以访问的标志是,当前节点没有孩子,或者当前节点的前一个节点是左右孩子中的一个。
#include<iostream>
#include<stack>
using namespace std;
struct Node{
char data;
Node *lchild;
Node *rchild;
};
Node*createTree(){
char x;
cin>>x;
if(x=='#')return NULL;
Node *root=new Node;
root->data=x;
root->lchild=createTree();
root->rchild=createTree();
return root;
}
void postTraversal(Node*root) {
stack<Node*>s;
Node *cur;
Node *pre=NULL;
s.push(root) ;
while(!s.empty()){
cur=s.top();
if((cur->lchild==NULL&&cur->rchild==NULL)||
(pre!=NULL&&(pre==cur->lchild||pre==cur->rchild))
){//如果当前节点没有孩子,或者前一个节点是当前的左右孩子之一,都可以访问了。
cout<<cur->data<<" ";
s.pop();
pre=cur;
}
else{
if(cur->rchild!=NULL)
s.push(cur->rchild);
if(cur->lchild!=NULL)
s.push(cur->lchild);
}
}
}
int main(){
//测试用例:1 2 4 # # 5 # # 3 # #
Node *root=createTree();
postTraversal(root);
return 0;
}