#include <iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef char TelemType;
typedef struct BinaryTreeNode {
TelemType data;
struct BinaryTreeNode *Left;
struct BinaryTreeNode *Right;
} Node;
typedef Node * BinTree;
Node* createBinaryTree() {
Node *p;
TelemType ch;
cin>>ch;
if(ch == '@') {
p = NULL;
} else {
p = (Node*)malloc(sizeof(Node));
p->data = ch;
p->Left = createBinaryTree();
p->Right = createBinaryTree();
}
return p;
}
void preOrder(Node* root) {
if( root ) {
cout<<root->data<<' ';
preOrder(root->Left);
preOrder(root->Right);
}
}
void inOrder(Node* root) {
if( root ) {
inOrder(root->Left);
cout<<root->data<<' ';
inOrder(root->Right);
}
}
void lastOrder(Node* root) {
if( root ) {
lastOrder(root->Left);
lastOrder(root->Right);
cout<<root->data<<' ';
}
}
int DepthOfTree(Node* root) {
if(root) {
return DepthOfTree(root->Left) > DepthOfTree(root->Right)? DepthOfTree(root->Left)+1:DepthOfTree(root->Right)+1;
}
if( root == NULL ) {
return 0;
}
}
int Leafnum(Node* root) {
if(!root) {
return 0;
} else if( (root->Left == NULL) && (root->Right == NULL) ) {
return 1;
} else {
return (Leafnum(root->Left) + Leafnum(root->Right)) ;
}
}
int main() {
BinTree root = NULL;
root = createBinaryTree();
printf("二叉树建立成功");
cout<<"二叉树深度为:"<<DepthOfTree(root)<<endl;
cout<<"二叉树叶子节点数为:"<<Leafnum(root)<<endl;
cout<<endl;
cout<<"前序遍历结果:"<<endl;
preOrder(root);
cout<<endl;
cout<<"中序遍历结果:"<<endl;
inOrder(root);
cout<<endl;
cout<<"后序遍历结果:"<<endl;
lastOrder(root);
cout<<endl;
return 0;
}
#include <cstdio>
#include <cstring>
const int maxn=105;
char pre[maxn],in[maxn];
struct node{
char data;
node* lch;
node* rch;
};
node* create(int prel,int prer,int inl,int inr){
if(prel>prer) return NULL;
node* root=new node;
root->data=pre[prel];
int k;
for(k=inl;k<=inr;k++) if(in[k]==pre[prel]) break;
int numleft=k-inl;
root->lch=create(prel+1,prel+numleft,inl,k-1);
root->rch=create(prel+numleft+1,prer,k+1,inr);
return root;
}
void postorder(node* root){
if(root==NULL) return;
postorder(root->lch);
postorder(root->rch);
printf("%c",root->data);
}
int main(){
while(scanf("%s%s",pre,in)==2){
int n=strlen(pre);
node* root=create(0,n-1,0,n-1);
postorder(root);
printf("\n");
}
return 0;
}