编写后序遍历二叉树的非递归算法
#include <iostream>
#include <stack>
typedef struct treenode{char data;struct treenode *left;struct treenode *right;
}treenode,*ptreenode;ptreenode buytreenode(char x)
{ptreenode n=(ptreenode) malloc(sizeof (treenode));n->data=x;n->left= nullptr,n->right= nullptr;return n;
}
ptreenode build_tree()
{ptreenode root= buytreenode('A');root->left= buytreenode('B');root->right= buytreenode('C');root->left->left= buytreenode('D');root->left->right= buytreenode('E');return root;
}void postorder(ptreenode root)
{std::stack<ptreenode> record;ptreenode pointer=root,pre= nullptr;while(pointer || !record.empty()){if(pointer) record.push(pointer),pointer=pointer->left;else{pointer=record.top();if(pointer->right&&pointer->right!=pre) pointer=pointer->right;else{printf("%3c",record.top()->data);record.pop();pre=pointer;pointer= nullptr;}}}
}
int main() {ptreenode root=build_tree();postorder(root);return 0;
}