typedef char E;
struct TreeNode {
E element;
struct TreeNode *left;
struct TreeNode *right;
struct TreeNode *parent;
int leftTag, rightTag;
};
typedef struct TreeNode *Node;
Node createNode(E element) {
Node node = malloc(sizeof(struct TreeNode));
if (node == NULL) return NULL;
node->left = node->right = NULL;
node->leftTag = node->rightTag = 0;
node->element = element;
return node;
}
Node pre = NULL;
void postOrder(Node root) {
if (root == NULL) return;
if (root->leftTag == 0) {
if (root->left != NULL)root->left->parent = root;
postOrder(root->left);
}
if (root->rightTag == 0) {
if (root->right != NULL)root->right->parent = root;
postOrder(root->right);
}
if (root->left == NULL) {
root->left = pre;
root->leftTag = 1;
}
if (pre && pre->right == NULL) {
pre->right = root;
pre->rightTag = 1;
}
pre = root;
}
void f(Node TwoTree) {
while (TwoTree && TwoTree->leftTag == 0)
TwoTree = TwoTree->left;
printf("%c", TwoTree->element);
while (TwoTree) {
if (TwoTree && TwoTree->rightTag == 1){
TwoTree = TwoTree->right;
printf("%c", TwoTree->element);
} else {
if (TwoTree->parent->right)
TwoTree = TwoTree->parent->right;
else
TwoTree = TwoTree->parent;
printf("%c", TwoTree->element);
}
}
}
int main() {
Node a = createNode('A');
Node b = createNode('B');
Node c = createNode('C');
Node d = createNode('D');
Node e = createNode('E');
a->left = b;
b->left = d;
a->right = c;
b->right = e;
postOrder(a);
f(a);
}