#include "stdio.h"
#include "stdlib.h"
#define M 100
int num[M] = {3, 9, 1, 33, 20, 18, 52, 0, 10, 7};
int n = 10;
typedef struct _Node{
int pos;
struct _Node* pare;
struct _Node* lf;
struct _Node* rt;
}Node, *pNode;
pNode st[M];
int top;
void RMQ_2_LCA(pNode* r){
pNode w;
int k, i;
top = -1;
for(i=0; i<n; i++){
w = (pNode)malloc(sizeof(Node));
w->pos = i;
w->lf = w->rt = 0;
k = top;
while(k>=0 && num[i]<num[st[k]->pos])
k--;
if(k>=0){
st[k]->rt = w;
w->pare = st[k];
}
if(k<top)
w->lf = st[k+1];
st[++k] = w;
top = k;
}
st[0]->pare = 0;
*r = st[0];
}
void show(pNode r){
if(!r) return;
printf("%d ", num[r->pos]);
show(r->lf);
show(r->rt);
}
void main(){
pNode root;
RMQ_2_LCA(&root);
show(root); printf("\n");
}
show函数打出来的不好看,自己调试,看看树的结构