#include<stdio.h>
#include <iostream>
#include <fstream>
#include <string>
struct TreeNode
{
struct TreeNode* left;
struct TreeNode* right;
char elem;
};
//根据前序和中序构造二叉树
void BinaryTreeFromOrderings(char* inorder, char* preorder, int length)
{
if(length == 0)
{
return;
}
TreeNode* node = new TreeNode;//Noice that [new] should be written out.
node->elem = *preorder;
int rootIndex = 0;
for(;rootIndex <length; rootIndex++)
{
if(inorder[rootIndex] == *preorder)
break;
}
BinaryTreeFromOrderings(inorder, preorder +1, rootIndex);
//Right
BinaryTreeFromOrderings(inorder + rootIndex + 1, preorder + rootIndex + 1, length - (rootIndex + 1));
printf("%c", node->elem);
return;
}
//根据中序和后序构造二叉树
TreeNode* BinaryTreeFromPostOrderings(char* inorder, char* aftorder, int length)
{
if(length == 0)
{
return NULL;
}
TreeNode* node = new TreeNode;//Noice that [new] should be written out.
node->elem = *(aftorder+length-1);
// std::cout<<node->elem<<std::endl;
printf("%c", node->elem);
int rootIndex = 0;
for(;rootIndex < length; rootIndex++)//a variation of the loop
{
if(inorder[rootIndex] == *(aftorder+length-1))
break;
}
node->left = BinaryTreeFromPostOrderings(inorder, aftorder , rootIndex);
node->right = BinaryTreeFromPostOrderings(inorder + rootIndex + 1, aftorder + rootIndex , length - (rootIndex + 1));
return node;
}
//统计叶子节点个数
void countLeaf(TreeNode* root,int &count){
if(root!=NULL){
if(root->left==NULL&&root->right==NULL){
count++;
}
countLeaf(root->left,count);
countLeaf(root->right,count);
}
}
//判断二叉树是否为排序二叉树
bool judge(TreeNode* root){
if(root==NULL){
return true;
}
TreeNode* tleft=root->left;
TreeNode* tright=root->right;
bool leftf=false,rightf=false,rootleft=false,rootright=false;
if(tleft==NULL||(tleft&&tleft->elem<=root->elem)){
rootleft=true;
}
if(tright==NULL||(tright&&tright->elem<=root->elem)){
rootright=true;
}
leftf=judge(tleft);
rightf=judge(tright);
return (leftf && rightf && rootleft && rootright);
}
int main()
{
char* pr="GDAFEMHZ";
char* in="ADEFGHMZ";
char* post="AEFDHZMG";
printf("前序:%s\n",pr);
printf("中序:%s\n",in);
printf("根据前序和中序序列输出后序序列\n");
BinaryTreeFromOrderings(in, pr, 8);
printf("\n");
printf("中序:%s\n",in);
printf("后序:%s\n",post);
printf("根据中序和后序序列输出后序序列\n");
TreeNode *root= BinaryTreeFromPostOrderings(in,post,8);
printf("\n");
int count=0;
countLeaf(root,count);
printf("叶节点个数:%d \n",count);
bool f=judge(root);
if (f){
printf("该二叉树是否为排序二叉树:yes \n");
}else printf("该二叉树是否为排序二叉树:no \n");
return 0;
}