给定一个层数小于等于10的二叉树,输出对其后序遍历的节点名序列。
输入包括一行,为由空格分隔开的各节点,按照二叉树的分层遍历顺序给出,每个节点形式如X(Y,num),X表示该节点,Y表示父节点,num为0,1,2中的一个,0 表示根节点,1表示为父节点的左子节点,2表示为父节点的右子节点。输出为一行,为后序遍历的结果。
输入:
A(0,0) B(A,1) C(A,2) D(B,1) E(B,2) F(C,1) G(D,1) H(D,2)
输出:
G H D E B F C A
#include<iostream> #include<map> #include<stack> using namespace std; struct btNode{ char c; btNode *left, *right; btNode(char ch) : c(ch), left(NULL), right(NULL){} }; bool firstFlag; /* void postOrder(btNode *root){ if(root == NULL){ return; } postOrder(root->left); postOrder(root->right); if(firstFlag){ firstFlag = 0; }else{ putchar(' '); } printf("%c", root->c); } */ void postOrder(btNode * root){ btNode *cur, *pre = NULL; stack<btNode*> sk; sk.push(root); while(!sk.empty()){ cur = sk.top(); if(cur->left == NULL && cur->right == NULL || pre != NULL && (pre == cur->left || pre == cur->right)){ sk.pop(); if(firstFlag){ firstFlag = 0; }else{ putchar(' '); } putchar(cur->c); }else{ if(cur->right){ sk.push(cur->right); } if(cur->left){ sk.push(cur->left); } } pre = cur; } } int main(){ // freopen("test.txt", "r", stdin); char ch, fa, lr; map<char, btNode*> mp; btNode *root, *p, *q; while(scanf("%c(%c,%c) ", &ch, &fa, &lr) == 3){ if(fa == '0'){ root = new btNode(ch); mp[ch] = root; }else{ p = mp[fa]; q = new btNode(ch); mp[ch] = q; if(lr == '1'){ p->left = q; }else{ p->right = q; } } } firstFlag = 1; postOrder(root); cout << endl; }