二叉树

(一)二叉树

1.A - Binary Tree Traversals

A binary tree is a finite set of vertices that is either empty or consists of a root r and two disjoint binary trees called the left and right subtrees. There are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. They are preorder, inorder and postorder. Let T be a binary tree with root r and subtrees T1,T2. 

In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder. 

In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder. 

In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r. 

Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence. 

InputThe input contains several test cases. The first line of each test case contains a single integer n (1<=n<=1000), the number of vertices of the binary tree. Followed by two lines, respectively indicating the preorder sequence and inorder sequence. You can assume they are always correspond to a exclusive binary tree. 
OutputFor each test case print a single line specifying the corresponding postorder sequence. 
Sample Input

9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6

Sample Output

7 4 2 8 9 5 6 3 1

解题思路:这是一道经典的根据二叉树的先序和中序遍历序列,求后序遍历
代码:
#include<iostream>
#include<cstdio>
using namespace std;
const int N=1010;
int pre[N],in[N],post[N];
int k;
struct node{
    int value;
    node *l;
    node *r;
    node(int value=0,node *l=NULL,node *r=NULL):value(value),l(l),r(r){}
};
//建树
void buildtree(int l,int r,int &t,node* &root)
{
    int flag=-1;
    for(int i=l;i<=r;i++)
    {
        if(in[i]==pre[t])
        {
           flag=i;
           break;
        }
    }
    if(flag==-1)
        return ;
    root=new node(in[flag]);//新建节点
    t++;
    if(flag>l)
        buildtree(l,flag-1,t,root->l);
    if(flag<r)
        buildtree(flag+1,r,t,root->r);
}
//求后序遍历
void postorder(node *root)
{
    if(root!=NULL)
    {
        postorder(root->l);
        postorder(root->r);
        post[k++]=root->value;
    }
}
//释放空间
void remove_tree(node *root)
{
    if(root==NULL)
        return ;
    remove_tree(root->l);
    remove_tree(root->r);
    delete root;
}
int main()
{
    int n,i,j;
    while(~scanf("%d",&n))
    {
        for(i=1;i<=n;i++)
            scanf("%d",&pre[i]);
        for(i=1;i<=n;i++)
            scanf("%d",&in[i]);
        node *root;
        int t=1;
        buildtree(1,n,t,root);
        k=0;        //记录节点个数
        postorder(root);
        for(i=0;i<n;i++)
        {
            if(i==0)
                printf("%d",post[i]);
            else
                printf(" %d",post[i]);
        }
        printf("
");
        remove_tree(root);
    }
    return 0;
}

2.B - The order of a Tree

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. 
Input
There are multiple test cases in an input file. The first line of each testcase is an integer n(n <= 100,000),represent the number of nodes.The second line has n intergers,k1 to kn,represent the order of a tree.To make if more simple, k1 to kn is a sequence of 1 to n. 
OutputOne line with n intergers, which are the order of a tree that generate the same tree with the least lexicographic. 
Sample Input
4

1 3 4 2
Sample Output
1 3 2 4
解题思路:这是一道二叉搜索树的应用题。
代码:
#include<iostream>
#include<cstdio>
using namespace std;

typedef struct node
{
    int value;
    struct node *l;
    struct node *r;
}*BTree;

void add(BTree &t,int e)
{
    if(t==NULL)
    {
        t=new node();
        t->value=e;
        t->l=t->r=NULL;
    }
    else if(t->value>e)
    {
        add(t->l,e);
    }
    else
    {
        add(t->r,e);
    }
}

void print(BTree b,bool flag)
{
    if(b==NULL)
        return;
    else{
            if(!flag)
                printf(" ");
        printf("%d",b->value);
        print(b->l,0);
        print(b->r,0);
    }
}

int main()
{
    int n,i,f;
    BTree t=NULL;
    while(~scanf("%d",&n))
    {
        for(i=0;i<n;i++)
        {
            scanf("%d",&f);
            add(t,f);
        }
        print(t,1);
        printf("
");
    }
    return 0;
}

3.C - 二叉搜索树

判断两序列是否为同一二叉搜索树序列

Input

开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。 
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。 
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。Output如果序列相同则输出YES,否则输出NO 
Sample Input

2
567432
543267
576342
0

Sample Output

YES
NO

解题思路:在二叉搜索数的基础上建立一个对比函数:用来查看两个二叉树是否为同一个,因此需要先建立一个目标树,其次通过每个测试用例建立对比树
然后比较目标树是否与对比树一致。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef struct node
{
    int value;
    struct node *l;
    struct node *r;
}*BTree;

bool flag=true;
void add(BTree &t,int e)
{
    if(t==NULL)
    {
        t=new node();
        t->value=e;
        t->l=t->r=NULL;
    }else if(t->value>e)
    {
        add(t->l,e);
    }else
    {
        add(t->r,e);
    }
}

void check(BTree &root,BTree &rom)
{
    if(root!=NULL&&rom!=NULL)
    {
        check(root->l,rom->l);
        if(root->value!=rom->value)
            flag=false;
        check(root->r,rom->r);
    }
    else if(root!=NULL||rom!=NULL)
        flag=false;
}

int main()
{
    int t,i,len,j;
    while(scanf("%d",&t)&&t!=0)
    {
        BTree T=NULL;
        char str[12];
        scanf("%s",str);
        for(i=0;i<strlen(str);i++)
            add(T,str[i]-'0');
        for(i=0;i<t;i++)
        {
            flag=true;
            BTree T2=NULL;
            scanf("%s",str);
            for(j=0;j<strlen(str);j++)
                add(T2,str[j]-'0');
            check(T,T2);
            if(flag)
                printf("YES
");
            else
                printf("NO
");
        }
    }
    return 0;
}

4.D - Hardwood Species

Hardwoods are the botanical group of trees that have broad leaves, produce a fruit or nut, and generally go dormant in the winter. 
America's temperate climates produce forests with hundreds of hardwood species -- trees that share certain biological characteristics. Although oak, maple and cherry all are types of hardwood trees, for example, they are different species. Together, all the hardwood species represent 40 percent of the trees in the United States. 

On the other hand, softwoods, or conifers, from the Latin word meaning "cone-bearing," have needles. Widely available US softwoods include cedar, fir, hemlock, pine, redwood, spruce and cypress. In a home, the softwoods are used primarily as structural lumber such as 2x4s and 2x6s, with some limited decorative applications. 

Using satellite imaging technology, the Department of Natural Resources has compiled an inventory of every tree standing on a particular day. You are to compute the total fraction of the tree population represented by each species.

Input

Input to your program consists of a list of the species of every tree observed by the satellite; one tree per line. No species name exceeds 30 characters. There are no more than 10,000 species and no more than 1,000,000 trees.

Output

Print the name of each species represented in the population, in alphabetical order, followed by the percentage of the population it represents, to 4 decimal places.

Sample Input

Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
Hickory
Pecan
Hard Maple
White Oak
Soft Maple
Red Oak
Red Oak
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow

Sample Output

Ash 13.7931
Aspen 3.4483
Basswood 3.4483
Beech 3.4483
Black Walnut 3.4483
Cherry 3.4483
Cottonwood 3.4483
Cypress 3.4483
Gum 3.4483
Hackberry 3.4483
Hard Maple 3.4483
Hickory 3.4483
Pecan 3.4483
Poplan 3.4483
Red Alder 3.4483
Red Elm 3.4483
Red Oak 6.8966
Sassafras 3.4483
Soft Maple 3.4483
Sycamore 3.4483
White Oak 10.3448
Willow 3.4483
Yellow Birch 3.4483
解题思路:这是一道红黑树问题(可以用STL中的map来处理字符串轻松解决)
#include<iostream>
#include<map>
#include<cstdio>
using namespace std;


map<string,int> mp;


int main()
{
    string s;
    int ans=0;
    while(getline(cin,s))
    {
        mp[s]++;
        ans++;
    }
    map<string,int>::iterator it;
    for(it=mp.begin();it!=mp.end();it++)
    {
        cout<<it->first<<" ";
        double d=it->second*1.0/ans*100;
        printf("%.4f
",d);
    }
    return 0;
}


 
 
原文地址:https://www.cnblogs.com/xiaofengzai/p/12359182.html