#include<iostream>
#include<stack>
using namespace std;
class Node
{
public:
int val;
Node* left;
Node* right;
Node(int val):val(val), left(NULL), right(NULL){}
};
//先序遍历
void preOrder(Node* root)
{
if (root == NULL)
{
return;
}
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
void NicepreOrder(Node* root)
{
stack<Node*> s;
if (root == NULL)
{
return;
}
s.push(root);
while (!s.empty())
{
Node* root = s.top();
s.pop();
cout << root->val << " ";
if (root->right != NULL)
{
s.push(root->right);
}
if (root->left != NULL)
{
s.push(root->left);
}
}
cout << endl;
}
//中序遍历
void inOrder(Node* root)
{
if (root == NULL)
{
return;
}
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
void NiceinOrder(Node* root)
{
stack<Node*> s;
if (root == NULL)
{
return;
}
while (!s.empty() || root != NULL)//?
{
if (root != NULL)
{
s.push(root);
root = root->left;
}
else
{
root = s.top();
s.pop();
cout << root->val << " ";
root = root->right;
}
}
cout << endl;
}
//后序遍历
void postOrder(Node* root)
{
if (root == NULL)
{
return;
}
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
void NicepostOrder(Node* root)
{
stack<Node*> s;
stack<Node*> s1;
if (root == NULL)
{
return;
}
s.push(root);
while (!s.empty())
{
Node* root = s.top();
s.pop();
s1.push(root);
if (root->left != NULL)
{
s.push(root->left);
}
if (root->right != NULL)
{
s.push(root->right);
}
}
while (!s1.empty())
{
Node* root = s1.top();
s1.pop();
cout << root->val << " ";
}
cout << endl;
}
int main()
{
Node* head = new Node(5);
head->left = new Node(3);
head->right = new Node(8);
head->left->left = new Node(2);
head->left->right = new Node(4);
head->left->left->left = new Node(1);
head->right->left = new Node(7);
head->right->left->left = new Node(6);
head->right->right = new Node(10);
head->right->right->left = new Node(9);
head->right->right->right = new Node(11);
// recursive
cout<<"==============recursive=============="<<endl;
cout<<"pre-order: "<<endl;
preOrder(head);
cout << endl;
cout<<"in-order: "<<endl;
inOrder(head);
cout<<endl;
cout<<"pos-order: "<<endl;
postOrder(head);
cout<<endl;
// unrecursive
cout<<"============unrecursive============="<<endl;
NicepreOrder (head);
NiceinOrder(head);
NicepostOrder (head);
getchar();
return 0;
}