HDU 5444 Elven Postman (2015 ACM/ICPC Asia Regional Changchun Online),hdu5444

來源:互聯網
上載者:User

HDU 5444 Elven Postman (2015 ACM/ICPC Asia Regional Changchun Online),hdu5444

【題目連結】:click here~~

【題目大意】:

HDU 5444

題意:在最初為空白的二叉樹中不斷的插入n個數。對於每個數,從根節點開始判斷,如果當前節點為空白,就插入當前節點,如果當前節點不為空白,則小於當前節點的值,插入右子樹,否則插入左子樹。

接著q次詢問,每次詢問一個值在二叉樹中從根節點開始的尋找路徑。


3

直接用二叉樹類比整個插入和詢問的過程

代碼:

/** Problem: HDU No.5444* Running time: 0MS* Complier: G++* Author: javaherongwei* Create Time: 12:15 2015/9/16 星期三* binary search tree*/#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>using namespace std;typedef long long LL;struct BST  // binary serach tree{    int data;    BST * leftchild;   //lson    BST * rightchild;  //rson    BST () {}    BST(int x){        //init value        data=x;        leftchild=rightchild=NULL;    }};void build(BST *&root,int key) // creat the tree{    if(key<root->data){        if(NULL==root->leftchild){            root->leftchild= new BST(key);            return;        }        else build(root->leftchild,key);    }    else{        if(NULL==root->rightchild){            root->rightchild= new BST(key);            return;        }        else build(root->rightchild,key);    }}void get_path(BST *root,int key) // query{    if(root->data==key){        puts("");        return ;    }    else if(key<root->data){     // lson        putchar('E');        get_path(root->leftchild,key);    }    else{        putchar('W');           //rson        get_path(root->rightchild,key);    }}int main(){    int t,rt,x,n,m;    scanf("%d",&t);    while(t--){        scanf("%d",&n);        scanf("%d",&rt);        BST *root= new BST(rt);        for(int i=1; i<n; ++i){            scanf("%d",&x);            build(root,x);        }        scanf("%d",&m);        int q;        while(m--){            scanf("%d",&q);            get_path(root,q);        }        root=NULL;    }    return 0;}/*Sample Input242 1 4 331 2 366 5 4 3 2 111Sample OutputEWEEEEEE*/



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.