日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

前序+中序--后序

發(fā)布時間:2025/3/15 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 前序+中序--后序 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

二叉樹的前序、中序、后序遍歷的定義: 前序遍歷:對任一子樹,先訪問跟,然后遍歷其左子樹,最后遍歷其右子樹; 中序遍歷:對任一子樹,先遍歷其左子樹,然后訪問根,最后遍歷其右子樹; 后序遍歷:對任一子樹,先遍歷其左子樹,然后遍歷其右子樹,最后訪問根。 給定一棵二叉樹的前序遍歷和中序遍歷,求其后序遍歷(提示:給定前序遍歷與中序遍歷能夠唯一確定后序遍歷)。

#include <stdio.h> #include <stdlib.h> #include<cstdio> #include<algorithm> #include <iostream> #include<stack> #include <string.h> using namespace std; //1 確定根,確定左子樹,確定右子樹。 //2 在左子樹中遞歸。 //3 在右子樹中遞歸。 //4 打印當前根。 char pre[100],mid[100]; struct node{char key;node *left,*right; }Tree[50]; int loc=0; node *Creat(){Tree[loc].left=Tree[loc].right=nullptr;return &Tree[loc++]; } node *Build(int s1,int e1,int s2,int e2){node *ans=Creat();ans->key=pre[s1];int root_index;for(int i=s2;i<=e2;i++){if(mid[i]==pre[s1]){root_index=i;break;}}if(root_index!=s2){ans->left=Build(s1+1,s1+(root_index-s2),s2,root_index-1);}if(root_index!=e2){ans->right=Build(s1+(root_index-s2)+1,e1,root_index+1,e2);}return ans; } void postOrder(node *T){if(T==nullptr) return;postOrder(T->left);postOrder(T->right);printf("%c",T->key); } int main(){while(scanf("%s",pre)!=EOF){scanf("%s",mid);loc=0;int len1=strlen(pre);int len2=strlen(mid);node *T=Build(0,len1-1,0,len2-1);postOrder(T);cout<<endl;}return 0; }

  

轉載于:https://www.cnblogs.com/anhuixuyin218/p/9124825.html

總結

以上是生活随笔為你收集整理的前序+中序--后序的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。