HDU 1710 二叉樹的遍曆,hdu1710二叉樹

來源:互聯網
上載者:User

HDU 1710 二叉樹的遍曆,hdu1710二叉樹

#include <iostream>#include <stack>using namespace std;typedef struct Node{     Node *l,*r;    //struct Node 與 Node  均可以  int num;}*tree;tree root;tree creat(int a[],int b[],int n){tree ss;for (int i=0;i<n;i++){if (a[0] == b[i]){            ss = (tree)malloc(sizeof(Node));ss->num = b[i];ss->l=creat(a+1,b,i);ss->r=creat(a+i+1,b+i+1,n-i-1);return ss;}}return NULL;}void post_order(tree h){     if (h !=NULL)     //if判斷一定不能少,因為到葉子的地方就停止了,     {post_order(h->l);post_order(h->r);if (root == h){cout<<h->num<<endl;}else    cout<<h->num<<" "; }}int main(){    int a[1000],b[1000],n,i;tree h;while (cin>>n){for(i=0;i<n;i++){cin>>a[i];}for (i=0;i<n;i++){cin>>b[i];}root = h = creat(a,b,n);post_order(h);}return 0;}


從先序遍曆與中序遍曆中得到根節點,再根據中序遍曆中根的左邊(左子樹)與右邊(右子樹),再遞迴找根。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.