順序存儲的二叉樹的最近的公共祖先問題(25 分)
設順序存儲的二叉樹中有編號為i和j的兩個結點,請設計算法求出它們最近的公共祖先結點的編號和值。
輸入格式:
輸入第1行給出正整數n(≤1000),即順序存儲的最大容量;第2行給出n個非負整數,其間以空格分隔。其中0代表二叉樹中的空結點(如果第1個結點為0,則代表一棵空樹);第3行給出一對結點編號i和j。
題目保證輸入正確對應一棵二叉樹,且1≤i,j≤n。
輸出格式:
如果i或j對應的是空結點,則輸出ERROR: T[x] is NULL
,其中x
是i或j中先發現錯誤的那個編號;否則在一行中輸出編號為i和j的兩個結點最近的公共祖先結點的編號和值,其間以1個空格分隔。
輸入樣例1:
15
4 3 5 1 10 0 7 0 2 0 9 0 0 6 8
11 4
輸出樣例1:
2 3
輸入樣例2:
15
4 3 5 1 0 0 7 0 2 0 9 0 0 6 8
12 8
輸出樣例2:
ERROR: T[12] is NULL
#include<stdio.h> #include<string.h> typedef struct node { int data; struct node *lc,*rc; }bitree; int main() { int i,n; int a[10000]; int x,y; int u,v; int count1,count2; scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d",&a[i]); } scanf("%d%d",&x,&y); if(!a[x]) { printf("ERROR: T[%d] is NULL\n",x); } else if(!a[y]) { printf("ERROR: T[%d] is NULL\n",y); } else { u=x;v=y; count1=count2=1; while(1) { if(u==1) { break; } u/=2; count1++; } while(1) { if(v==1) { break; } v/=2; count2++; } if(count1>count2) { while(count1!=count2) { count1--; x/=2; } } else if(count2>count1) { while(count1!=count2) { count2--; y/=2; } } while(x!=y) { x/=2; y/=2; } printf("%d %d\n",x,a[x]); } return 0; }