【题目链接】:click here~~
【题目大意】:
题意:在最初为空的二叉树中不断的插入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 Input
2
4
2 1 4 3
3
1 2 3
6
6 5 4 3 2 1
1
1
Sample Output
E
WE
EEEEE
*/版权声明:本文为博主原创文章,未经博主允许不得转载。
HDU 5444 Elven Postman (2015 ACM/ICPC Asia Regional Changchun Online)
原文地址:http://blog.csdn.net/u013050857/article/details/48492181