#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct Node
{
char value;
struct Node *leftChild;
struct Node *rightChild;
int maxLeft;//本節點到左子樹所有節點的最大距離
int maxRight;//本節點到右子樹所有節點的最大距離
}TreeNode;
int maxLength=0;
//根據中序和前序序列構造二叉樹
TreeNode *CreateFromMidPre(char mid[],int midLeft,int midRight,char pre[],int preLeft,int preRight)
{
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
int midLeft1,midRight1,preLeft1,preRight1,rootPos=0;
if(midRight-midLeft != preRight-preLeft)
{
printf("錯誤:輸入的中序和前序序列結點個數不一樣!\n");
return node;
}
node->value = pre[preLeft];
node->leftChild = NULL;
node->rightChild = NULL;
for(;mid[rootPos]!=pre[preLeft];rootPos++);
if(rootPos!=midLeft)
{
midRight1 = rootPos-1;
preRight1 = rootPos-midLeft+preLeft;
node->leftChild = CreateFromMidPre(mid,midLeft,midRight1,pre,preLeft+1,preRight1);
}
if(rootPos!=midRight)
{
midLeft1 = rootPos+1;
preLeft1 = rootPos-midLeft+preLeft+1;
node->rightChild = CreateFromMidPre(mid,midLeft1,midRight,pre,preLeft1,preRight);
}
return node;
}
void FindMax(TreeNode *pTree)
{
if(pTree->leftChild==NULL)
pTree->maxLeft=0;
else
{
FindMax(pTree->leftChild);
//某節點到左子樹的所有節點的最大距離為左子樹到其兩個子樹所有節點最大距離較大的加一
pTree->maxLeft=(pTree->leftChild->maxLeft > pTree->leftChild->maxRight?pTree->leftChild->maxLeft:pTree->leftChild->maxRight)+1;
}
if(pTree->rightChild==NULL)
pTree->maxRight=0;
else
{
FindMax(pTree->rightChild);
//某節點到右子樹的所有節點的最大距離為右子樹到其兩個子樹所有節點最大距離較大的加一
pTree->maxRight=(pTree->rightChild->maxLeft > pTree->rightChild->maxRight?pTree->rightChild->maxLeft:pTree->rightChild->maxRight)+1;
}
if(maxLength<pTree->maxLeft+pTree->maxRight)
maxLength=pTree->maxLeft+pTree->maxRight;
}
int main()
{
TreeNode *root1;
char preSeq[20],midSeq[20];
int i=0,numNode;
printf("請輸入節點總數:\n");
scanf("%d",&numNode);
fflush(stdin);
printf("請輸入先序序列:\n");
for(i=0;i<numNode;i++)
scanf("%c",preSeq+i);
fflush(stdin);
printf("請輸入中序序列:\n");
for(i=0;i<numNode;i++)
scanf("%c",midSeq+i);
fflush(stdin);
root1=CreateFromMidPre(midSeq,0,i-1,preSeq,0,i-1);
FindMax(root1);
printf("最遠的兩個節點距離為:%d\n",maxLength);
return 1;
}