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*/
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。