#include "stdafx.h"
#include<iostream>
#include<stack>
using namespace std;
typedef struct binode {
binode* lchild, *rchild;
char data;
}binode,*bitree;
int aftorder_bitree_create(bitree &T) {
stack<bitree>S;
bitree Q,D;
char ch = getchar();
do {
int k = 0;
if (ch != '#'&&S.size()==0)exit(-1);
while (ch== '#') {
k++;
ch = getchar();
} ;
switch (k) {
case 0:
if (S.size() > 1) {
if (!(Q = new(nothrow)binode))exit(-1);
if (!(D = new(nothrow)binode))exit(-1);
D->data = ch;
Q = S.top();
S.pop();
D->rchild = Q;
Q = S.top();
S.pop();
D->lchild = Q;
S.push(D);
}
else exit(-1); break;
case 1:
if (S.size()>0) {
if (!(Q = new(nothrow)binode))exit(-1);
if (!(D = new(nothrow)binode))exit(-1);
Q = S.top();
S.pop();
D->lchild = Q;
D->rchild = NULL;
D->data = ch;
S.push(D);
}
else exit(-1); break;
default:
Q=NULL;
for (int i = 1; i < k; i++) {
if (!(D = new(nothrow)binode))exit(-1);
D->data = ch;
D->lchild = NULL;
D->rchild = Q;
Q = D;
if (i<k-1&&(ch = getchar()) == '#')exit(-1);
}
S.push(D);
break;
}
ch = getchar();
} while (ch != 10 || S.size() != 1);
T = D;
return 1;
}
int main()
{
bitree T;
if (!(T = new(nothrow)binode))exit(-1);
aftorder_bitree_create(T);
//input:##a###yxb#c#d###qp#o#ef
getchar();
return 0;
}
C++后序建立二叉树
最新推荐文章于 2024-04-26 13:02:18 发布