創建樹結點的結構:1、數據 2、其父節點所在位置
創建容納整棵樹的結構:1、樹的所有結點 2、結點數
創建樹:通過循環,給整棵樹每個結點賦值,並記錄其父節點所在位置
尋找公共結點:通過循環找到包含所要尋找的數據的兩個結點,用兩個數組分別記錄下他們的父節點,並以此向上,直到記錄到根結點。
雖然比較兩個數組,當兩個數組中所記錄的父節點位置第一次相同時,則爲最近公共父節點。
#include <stdio.h>
#include <stdlib.h>
#define Maxsize 100
typedef struct _btnode
{
char data; //結點數據
int parent; //父節點所在位置
}Btnode;
typedef struct _bttree
{
Btnode node[Maxsize]; //此樹結構包含每一個結點
int n; //記錄結點數
}Bttree;
Bttree CreateTree();
char Commonfather(Bttree,char,char);
int main()
{
char c1,c2,father;
Bttree aTree;
printf("請創建一顆樹");
aTree=CreateTree();
fflush(stdin);
printf("請輸入需要查找的兩個結點:\n");
printf("第一個結點:\n");
scanf("%c",&c1);
fflush(stdin);
printf("第二個結點:\n");
scanf("%c",&c2);
father=Commonfather(aTree,c1,c2);
printf("他們的最近公共結點是:\n");
printf("%c",father);
getchar();
return 0;
}
Bttree CreateTree()
{
printf("建立一顆新樹:\n");
int i,n; //定義循環變量、定義結點數
int parentID; //定義父節點位置
char ch; //定義數據域
Bttree newTree; //定義一顆新樹
printf("請輸入這棵樹的結點數:\n");
scanf("%d",&n);
newTree.n=n;
getchar();
printf("請輸入這棵樹的結點:");
printf("格式爲data parent:\n");
for(i=0;i<n;i++)
{
scanf("%c %d",&ch,&parentID);
newTree.node[i].data=ch;
newTree.node[i].parent=parentID;
getchar();
}
return newTree;
}
char Commonfather(Bttree aTree,char c1,char c2)
{
int i,k,m,p,h;
int a[100],b[100]; //定義兩個數組,用於接收兩個結點的所有父節點
for(i=0;i<aTree.n;i++)
{
if(aTree.node[i].data==c1)
{
k=aTree.node[i].parent; //用k接收c1的父親結點
}
if(aTree.node[i].data==c2)
{
m=aTree.node[i].parent; //用m接收c2的父親結點
}
}
int j=0;
int d=0;
while(k!=-1) //當父親結點不是根結點時,循環
{
a[j]=k; //用新創建數組接收父親結點
j++;
k=aTree.node[k].parent; //把父親結點的父親結點賦值給k
}
a[j]=-1; //最後一個結點爲根結點
while(m!=-1)
{
b[d]=m;
d++;
m=aTree.node[m].parent;
}
b[d]=-1;
for(p=0;p<=j;p++)
{
h=a[p];
for(i=0;i<d;i++)
{
if(h==b[i])
{
return aTree.node[h].data;
}
}
}
}