// 先序(附带叶子标记)建树
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
#include<string>
using namespace std;
struct node
{
char data;
node* lchild;
node* rchild;
};
void print_firstroot(node* r)
{
printf("%c",r->data);
if(r->lchild!=NULL)
print_firstroot(r->lchild);
if(r->rchild!=NULL)
print_firstroot(r->rchild);
return;
}//先根遍历
void print_secondroot(node *r)
{
if(r->lchild!=NULL)
print_secondroot(r->lchild);
printf("%c",r->data);
if(r->rchild!=NULL)
print_secondroot(r->rchild);
return;
}//中根遍历
void print_lastroot(node *r)
{
if(r->lchild!=NULL)
print_lastroot(r->lchild);
if(r->rchild!=NULL)
print_lastroot(r->rchild);
printf("%c",r->data);
return;
}//后根遍历
int main()
{
stack<node*> sta;
char* str = new char[100];
gets(str);
//printf("%s",str);
int pos = 0;
int len = strlen(str);
node* root = new node;
node* tmp;
root->data = str[pos++];
root->lchild = NULL;
root->rchild = NULL;
sta.push(root);
while(pos < len)
{
while(true)
{
node* nl = new node;
nl->data = str[pos];
nl->lchild = NULL;
nl->rchild = NULL;
if(str[pos]=='*')
{
free(nl);
break;
}
sta.top()->lchild = nl;
sta.push(nl);
++pos;
}
tmp = sta.top();
sta.pop();
++pos;
while(str[pos]=='*')
{
if(!sta.empty())
{
tmp = sta.top();
sta.pop();
}
++pos;
}
if(pos >= len)
break;
node* nr = new node;
nr->data = str[pos];
nr->lchild = NULL;
nr->rchild = NULL;
sta.push(nr);
tmp->rchild = nr;
++pos;
}
print_firstroot(root);
printf("\n");
print_secondroot(root);
printf("\n");
print_lastroot(root);
printf("\n");
return 0;
}
先序列表建二叉树(带结束标识)
最新推荐文章于 2021-09-06 00:00:50 发布