#include <iostream>
#include <stack>
using namespace std;
struct Node{
int val;
Node* left;
Node* right;
Node(int x_) : val(x_), left(NULL), right(NULL){}
};
void InOrder(Node* root);
void PostOrder(Node* root);
void PreOrder(Node* root);
void CreateTree(Node** root)
{
int x;
Node *p;
if (*root == NULL){
cout << "plz input the root value(can't be 0): ";
cin >> x;
p = new Node(x);
(*root) = p;
}
cout << "input " << (*root)->val << "'s lchild(0 to end): ";
if (cin >> x && x != 0){
p = new Node(x);
(*root)->left = p;
}
cout << "input " << (*root)->val << "'s rchild(0 to end): ";
if (cin >> x && x != 0){
p = new Node(x);
(*root)->right = p;
}
if ((*root)->left)
CreateTree(&((*root)->left));
if ((*root)->right)
CreateTree(&((*root)->right));
}
int main()
{
Node *root = NULL;
CreateTree(&root);
cout << "InOrder..." << endl;
InOrder(root);
cout << "
PreOrder..." << endl;
PreOrder(root);
cout << "
PostOrder..." << endl;
PostOrder(root);
return 0;
}
void InOrder(Node *root)
{//为嘛我觉得这个很不好理解呢?
if (root == NULL) return;
stack<Node*> s;
Node *p = root;
while (p != NULL || !s.empty()){
while (p != NULL){
s.push(p);
p = p->left;
}
if (!s.empty()){
p = s.top();
cout << p->val << " ";
s.pop();
p = p->right;
}
}
}
void PostOrder(Node* root)
{
Node *p = root;
stack<Node*> s;
Node *visited;
s.push(p);
while (!s.empty()){
p = s.top();
if ((p->left == NULL && p->right == NULL) || p->left == visited || p->right == visited){
cout << p->val << " ";
visited = p;
s.pop();
}else {
if (p->right && p->right != visited)
s.push(p->right);
if (p->left && p->left != visited)
s.push(p->left);
}
}
}
void PreOrder(Node* root)
{
if (root == NULL) return;
stack<Node*> s;
Node* p = root;
while (p != NULL){
cout << p->val << " ";
if (p->right) s.push(p->right);
if (p->left)
p = p->left;
else if (!s.empty()){
p = s.top();
s.pop();
}else
return;
}
}