HDU
来源:互联网 发布:交通枢纽大数据 编辑:程序博客网 时间:2024/05/21 11:17
As we know,the shape of a binary search tree is greatly related to the order of keys we insert. To be precisely:
1. insert a key k to a empty tree, then the tree become a tree with
only one node;
2. insert a key k to a nonempty tree, if k is less than the root ,insert
it to the left sub-tree;else insert k to the right sub-tree.
We call the order of keys we insert “the order of a tree”,your task is,given a oder of a tree, find the order of a tree with the least lexicographic order that generate the same tree.Two trees are the same if and only if they have the same shape.
1. insert a key k to a empty tree, then the tree become a tree with
only one node;
2. insert a key k to a nonempty tree, if k is less than the root ,insert
it to the left sub-tree;else insert k to the right sub-tree.
We call the order of keys we insert “the order of a tree”,your task is,given a oder of a tree, find the order of a tree with the least lexicographic order that generate the same tree.Two trees are the same if and only if they have the same shape.
41 3 4 2
1 3 2 4
题意:构建二叉搜索树,输出按字典序最小的插入方式使得和构建的二叉搜索树一样;
思路:构建好二叉搜索树,直接输出前序遍历(要想插入和原图一样的话,只有先序遍历最小了,自己好好想想);
代码:
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;#define Max 100010int f;struct node{int tt;node *left;node *right;node(int k){tt = k;left = NULL;right = NULL;}};node *insert(node *root,int k) // 插入值,构建二叉搜索树; {if(root==NULL){node *pp = new node(k);return pp;}else{if(k<root->tt)root->left = insert(root->left,k);else root->right = insert(root->right,k);return root;}}void prodfs(node *root) // 输出先序遍历; {if(root==NULL)return ;if(!f){printf("%d",root->tt);f=1;}else printf(" %d",root->tt);prodfs(root->left);prodfs(root->right);}int main(){int i,j,n;while(~scanf("%d",&n)){node *root=NULL;int k;f=0;for(i=0;i<n;i++){scanf("%d",&k);root = insert(root,k);}prodfs(root);printf("\n");}return 0;}
阅读全文
0 0
- hdu
- hdu
- HDU
- hdu ()
- hdu
- hdu
- HDU
- HDU
- hdu
- hdu
- HDU
- Hdu
- hdu
- hdu-
- hdu
- hdu
- hdu
- HDU
- 定义函数
- 机器学习应用——sklearn自带数据集训练(支持向量机分类)
- 【贪心+优先队列 / 并查集】【cofun1025】工作安排
- sqlmap 简单操作与数据库账户密码破解
- 寻找单链表的倒数第四个节点
- HDU
- JSTL(第二节)
- WampSever 64 虚拟站点的构建
- hdu 4436 后缀自动机算和
- 经典算法题1:找出数组中只出现一次的数字,其它数字都出现了两次
- leetcode解题方案--016--3 sum closest
- httpclient封装别人接口
- y的值
- docker 常用命令整理