#include
#include
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct Node {
int data;
struct Node *left;
struct Node *right;
Node(int x) {
data = x;
left = NULL;
right = NULL;
}
};
void PostorderVisitTree(struct Node *root)
{
if (root == NULL) return;
std::stacks;
struct Node *cur = root;
struct Node *prev = NULL;
while(cur != NULL || !s.empty()) {
while(cur != NULL) {
s.push(cur);
cur = cur->left;
}
if (!s.empty()) {
cur = s.top();
if (cur->right == NULL || cur->right == prev) {
printf("%d ", cur->data);
prev = cur;
s.pop();
cur = NULL;
} else {
cur = cur->right;
}
}
}
}
int main(int argc, char** argv)
{
Node *root = new Node(1);
root->left = new Node(3);
root->left->left = new Node(2);
root->left->right = new Node(1);
root->left->right->left = new Node(1);
root->right = new Node(-1);
root->right->left = new Node(4);
root->right->left->left = new Node(1);
root->right->left->right = new Node(2);
root->right->right = new Node(5);
root->right->right->right = new Node(2);
PostorderVisitTree(root);
return 0;
}
输出结果:
2 1 1 3 1 2 4 2 5 -1 1