當前位置:成語大全網 - 書法字典 - c語言根據層次遍歷和中間遍歷找到二叉樹的前序遍歷和後序遍歷。下面是我的樹函數,有註釋。

c語言根據層次遍歷和中間遍歷找到二叉樹的前序遍歷和後序遍歷。下面是我的樹函數,有註釋。

#包含“cstdio”

#包括“矢量”

#包含“cstring”

#包含“算法”

使用命名空間std

const int maxn = 30

結構節點{

int數據;

node * lchild

node * rchild

};

int n;

int in[maxn];

bool vis[maxn]= { false };

向量& ltint & gtlev

節點*創建(向量& ltint & gtlev,int inl,int inr){

if(lev.size()==0)返回NULL

如果(inl & gtinr)返回NULL

//printf(" 00 \ n ");

node* root=新節點;

root-& gt;data = lev[0];

int k;

for(k = inl;k & lt=印度盧比;k++){

if(lev[0]==in[k])

打破;

}

for(int j = inl;j & lt= k-1;j++)

vis[in[j]]= true;

向量& ltint & gttempLeft,tempRight//在主體中創建新函數

for(int I = 1;我& ltlev . size();i++){

if(vis[lev[i]]==true)

templeft . push _ back(lev[I]);

其他

temp right . push _ back(lev[I]);

}

root-& gt;lchild =create(tempLeft,inl,k-1);

root-& gt;rchild =create(tempRight,k+1,INR);

返回根目錄;

}

無效預訂(節點*根){

if(root==NULL)

返回;

printf("%d ",root-& gt;數據);

前序(根->;l child);

前序(根->;rchild);

}

int main(){

scanf("%d ",& ampn);

int x;

for(int I = 0;我& ltn;i++){

scanf("%d ",& ampx);

lev . push _ back(x);

}

for(int j = 0;j & ltn;j++)

scanf("%d ",& ampin[j]);

node *root =create(lev,0,n-1);

前序(根);

返回0;

}