顺序存储的二叉树求两个结点的最近的公共祖先结点

#include 
#define MAXSIZE 100
using namespace std;
typedef struct Tnode
{
    int data;
    bool isExist;
}Tnode;
typedef struct SequenceTree
{
   struct Tnode tree[MAXSIZE];
   int length;
}SequenceTree;

int getCommonAncestor(int i,int j,SequenceTree seqTree)
{
    //两个结点不断往上找祖先
   while(i!=j)
   {
       if(i>j)
        i=i/2;
       else if(j>i)
        j=j/2;
       else
        return i;


   }
}
int main()
{
    struct SequenceTree seqTree;
    seqTree.length=10;//顺序表存储的二叉树的结点个数
    //赋值 暂时将每个位置上都放有元素
    for(int i=1;i<=seqTree.length;++i)
    {
        cin>>seqTree.tree[i].data;
    }
    int i=0,j=0;
    cin>>i>>j;
    int index=getCommonAncestor(i,j,seqTree);
    cout<<"共同祖先元素为"<<seqTree.tree[index].data;


    return 0;
}

你可能感兴趣的:(考研数据结构编程题)