HDU 5444 Elven Postman
2016-05-25 20:52
411 查看
题目分析
就是一个暴力建树,还有一个暴力查询的题。不过要知道怎么建还只要找规律的,大家可以发现,如果给定一个数值如果比根的值小,那么往根的左边走,不是则往右边走。(当然如果根没有值,直接将该数值填到根结点就可以了)。同理,往左后者往右的时候如果该部分为空,直接将该值填进去即可。同时每次执行完都要删除这个数,并且把根设置为空。
#include <cstdio> #include <cstring> #include <iostream> #include <cstdlib> using namespace std; struct BTNode { int data; struct BTNode *left,*right; }; BTNode *root; void build(int x) { BTNode *temp = (BTNode *)malloc(sizeof(BTNode)); temp->data = x; temp->left = temp->right = NULL; if(root == NULL) root = temp; else { BTNode *pre; BTNode *cur = root; while(cur != NULL) { pre = cur; if(cur->data > x) cur = cur->left; else cur = cur->right; } if(pre->data > x) pre->left = temp; else pre->right = temp; } } void query(int x) { BTNode *temp = root; while(temp->data != x) { if(temp->data > x) { printf("E"); temp = temp->left; } else { printf("W"); temp = temp->right; } } } void Delete(BTNode *temp) { if(temp != NULL) { Delete(temp->left); Delete(temp->right); free(temp); } } int main() { int T; scanf("%d", &T); while(T--) { root = NULL; int n,q,x; scanf("%d", &n); while(n--) { scanf("%d", &x); build(x); } scanf("%d", &q); while(q--) { scanf("%d", &x); query(x); printf("\n"); } Delete(root); } return 0; }
相关文章推荐
- C++作业6
- codefoeces 414A (构造)
- 23种设计模式(10):命令模式
- 关系型数据库和非关系型数据库
- 提交表单用ajax判断登录正确并跳转页面的方法
- 动态存储分配及深复制 —我的数组类
- 解决Deprecated: preg_replace(): The /e modifier is deprecated, use
- 用css3选择器给你要的第几个元素添加不同样式方法【转发】
- 【转】Mybatis框架结构与基本原理
- leetcode笔记—生成最大的 数组Create Maximum Number
- linux文本管理工具sed
- Java 实现导出excel表 POI
- 使用ThinkPHP框架快速搭建网站(通俗易懂)
- java设计模式-组合模式
- C++第六次实验———循环复习
- ECshop Strict Standards: Only variables should be passed by reference in解决办法
- PAT-1003
- elastic资料整理
- view的setTag() 和 getTag()应用
- 培训行业