Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9879 | Accepted: 6210 |
Description
D
/ \
/ \
B E
/ \ \
/ \ \
A C G
/
/
F
Input
Output
Sample Input
DBACEGF ABCDEFG BCAD CBAD
Sample Output
ACBFGED CDAB
题目大意:给出二叉树的先序,中序序列,求二叉树的后序序列。
#include <stdio.h> #include <string.h> #include <iostream> #include <stack> using namespace std; typedef struct node { char data; node *lchild; node *rchild; node() { lchild = rchild = NULL; } }TreeNode; //二叉树的非递归后序遍历 TreeNode *BuildTree(char *pre, char *in, int n) { TreeNode *pNode; int k; char *p; if (n <= 0) { return NULL; } pNode = new TreeNode;//新建节点 pNode->data = *pre; for (p = in; p < in + n; p++)//在中序序列中找等于*pre的位置k { if (*p == *pre)//pre指向根节点 { break;//找到后退出,从而确定根节点在in中的位置 } } k = p - in;//左子树的长度 pNode->lchild = BuildTree(pre + 1, in, k);//递归构造左子树 pNode->rchild = BuildTree(pre + k + 1, p + 1, n - k - 1);//递归构造右子树 return pNode;//返回根节点 } //二叉树的非递归后序遍历 void PostOrder(TreeNode *pRoot) { stack<TreeNode *> Stack; TreeNode *p = pRoot; TreeNode *q; do { while(p != NULL) { Stack.push(p); p = p->lchild; } q = NULL; while(!Stack.empty()) { p = Stack.top(); if (q == Stack.top()->rchild) { printf("%c", Stack.top()->data); q = Stack.top(); Stack.pop(); } else { p = p->rchild; break; } } } while (!Stack.empty()); } //删除二叉树节点 void DeleteNode(TreeNode *pRoot) { if (pRoot != NULL) { DeleteNode(pRoot->lchild); DeleteNode(pRoot->rchild); } delete pRoot; } int main() { char pre[30], in[30]; while(scanf("%s%s", pre, in) != EOF) { TreeNode *pRoot = BuildTree(pre, in, strlen(in)); PostOrder(pRoot); printf("\n"); DeleteNode(pRoot); } return 0; }