hdu 1710:Binary Tree Traversals

來源:互聯網
上載者:User

給出幾組二叉樹的先序和中序遍曆的節點序列,求出該二叉樹的後序遍曆序列。


先序遍曆中第一個一定是根節點,然後找先序遍曆中下一個節點在中序遍曆中是在根節點的左邊還是右邊,左邊則該節點在根結點的左子樹中,右邊則在右子樹中。根據該節點在根結點的哪一側往那側找,如果那一側沒有節點,就把這個節點添加上去,否則以那個節點為根節點繼續尋找,直到構建完整個二叉樹。最後用後序遍曆輸出二叉樹。


代碼:

#include <cstdio>#include <cstring>#include <iostream>using namespace std;struct node{    int num;    node *l,*r;    node(int x):num(x),l(NULL),r(NULL){}};int n;int DLR[1005],LDR[1005];void insert(node *h,int x){    bool flag=0;    for(int i=0;i<n;i++){        if(LDR[i]==h->num) flag=1;        if(LDR[i]==x) break;    }    if(!flag){        if(h->l==NULL) {            node *n=new node(x);            h->l=n;            return;        }        else insert(h->l,x);    }    else {        if(h->r==NULL) {            node *n=new node(x);            h->r=n;            return;        }        else insert(h->r,x);    }}void postOrder(node *h){    if(h->l!=NULL) postOrder(h->l);    if(h->r!=NULL) postOrder(h->r);    printf("%d%s",h->num,((--n)==0)?"\n":" ");}int main(){    //freopen("in.txt","r",stdin);    while(cin>>n){        for(int i=0;i<n;i++) cin>>DLR[i];        for(int i=0;i<n;i++) cin>>LDR[i];        node h(DLR[0]);        for(int i=1;i<n;i++){            insert(&h,DLR[i]);        }        postOrder(&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.