1. 程式人生 > >根據先序遍歷和中序遍歷推後序遍歷C語言

根據先序遍歷和中序遍歷推後序遍歷C語言

事實上,一箇中序遍歷的演算法中入棧的過程中,如果你把每個入棧的結點儲存起來,你會發現這些結點就是先序遍歷的結果,同樣,出棧就是中序遍歷,如下圖
在這裡插入圖片描述

  • 核心演算法
    在這裡插入圖片描述
    先序遍歷的第一個結點一定是根結點,也是後序遍歷的最後一個結點,找到它在中序中的位置 i ,那麼 i 的左邊就是左子樹,右邊是右子樹,遞迴的求解左右兩邊
  • 程式碼
#include <stdio.h>
#include <stdlib.h>
#define SIZE 6
//
int pre[6]={1,2,3,4,5,6};//先序遍歷陣列 
int in[6]={3,2,4,1,6,5};//中序遍歷 陣列 
int post[
6]={0};//後序遍歷陣列 void CreatePost(int first,int mid,int last,int n) { printf("------%d-------\n",first); if(n==0){ return; } if(n==1) { post[last]=pre[first]; return; } int root=pre[first]; post[last+n-1]=root; int i; for(i=0;i<6;i++) { if(root==in[i+mid]) break; } int L=i; int R
=n-L-1; CreatePost(first+1,mid,last,L); CreatePost(first+L+1,mid+L+1,last+L,R); } int main(int argc, char** argv) { CreatePost(0,0,0,6); for(int i=0;i<6;i++) printf("%d ",post[i]); return 0; }