数据结构-树与森林-双亲表示法

版权声明:转载请注明出处。 https://blog.csdn.net/baidu_38304645/article/details/83176898

 以一组连续空间存储结点,各结点附设指示器指示其双亲结点的位置(数据域加双亲下标域)。

首先是辅助宏:

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -1
#define UNDERFLOW -2
#define NULL 0
#define MAX_PTREE_SIZE 50010 //树的最大结点数目
typedef int Status;
typedef int TElemType;

树与森林的双亲表示法存储结构定义:

typedef struct TNode{
    //树的结点
   TElemType data;
   int parent; //双亲下标
   int flag;  //标记
   bool ba; //是否是平衡二叉树
   int lchild,rchild; //左右孩子下标
}TNode;
typedef TNode PTree[MAX_PTREE_SIZE];

在二叉树PT中 找包含a,b两结点的最小子树。

int FindSmallestPTree(PTree PT,int a,int b){
    //在二叉树PT中 找包含a,b两结点的最小子树
    int x=a;
    while(PT[x].parent){ //a结点不断向上直到根节点 并把走过的结点标记修改为1
       PT[x].flag=1;
       x=PT[x].parent;
    }
    PT[x].flag=1;
    int y=b;
    while(!PT[y].flag) //b结点不断向上直到遇到flag 为1的结点 就是最小子树根节点
        y=PT[y].parent;
    x=a;
    while(PT[x].parent){ //a结点不断向上直到根节点 并把走过的结点标记修改为1
        //别忘了每次都消除标记
       PT[x].flag=0;
       x=PT[x].parent;
    }
    return y;
}

猜你喜欢

转载自blog.csdn.net/baidu_38304645/article/details/83176898