代码如下:
struct Node{
Node(int _data):data(_data),left(NULL),right(NULL){}
int data;
Node* left;
Node* right;
};
void initTree(Node** head){
*head=new Node(1);
(*head)->left=new Node(2);
(*head)->right=new Node(3);
(*head)->left->left=new Node(4);
(*head)->left->right=new Node(5);
}
void desTree(Node* head){
if(head->left) desTree(head->left);
if(head->right) desTree(head->right);
delete head;
}
void preNonRecursive(Node* head){
stack<Node*> s;
s.push(head);
cout<<"pre order is :";
while(!s.empty()){
Node* n1=s.top();
s.pop();
cout<<n1->data<<" ";
if(n1->right!=NULL) s.push(n1->right);
if(n1->left!=NULL) s.push(n1->left);
}
cout<<endl;
}
void inNonRecursive(Node* head){
stack<Node*> s;
Node* cur=head;
cout<<"in order is:";
while(!s.empty()||cur!=NULL){
if(cur!=NULL){
s.push(cur);
cur=cur->left;
}else{
cur=s.top();s.pop();
cout<<cur->data<<" " ;
cur=cur->right;
}
}
cout<<endl;
}
void postNonRecursive(Node* head){
stack<Node*> s,sVisit;
s.push(head);
while(!s.empty()){
Node* p=s.top();s.pop();
sVisit.push(p);
if(p->left) s.push(p->left);
if(p->right) s.push(p->right);
}
cout<<"post order is :";
while(!sVisit.empty()){
Node* p=sVisit.top();sVisit.pop();
cout<<p->data<<" " ;
}
cout<<endl;
}
int main(){
Node* head;
initTree(&head);
preNonRecursive(head);
inNonRecursive(head);
postNonRecursive(head);
desTree(head);
return 0;
}