hdu3999 The order of a Tree(BST)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Flynn_curry/article/details/60780553


http://acm.hdu.edu.cn/showproblem.php?pid=3999

题意:给你一个序列可以构成一个二叉搜索树,求此二叉搜索树字典序最小的输入序列。


思路:hdu3971的弱化版。建树的基本思想是插入节点和根比较大小,根肯定要先确定,而插左插右是无所谓的。要想字典序小,肯定是先插小的,那BST正好是左边节点比根小,所以就是先插根,再插左,最后右,正好是前序遍历。


ps:不知道为啥把cnt放成preorder的局部变量老是格式错误,还是全局方便= =


#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <math.h>
#include <iostream>

using namespace std;

typedef long long ll;
const int N = 100005;

typedef struct Tree
{
    Tree *left;
    Tree *right;
    int val;
}Tree;

Tree *root;
int cnt, n;

Tree *creat(int num)
{
    Tree *node = (Tree*)malloc(sizeof(Tree));
    node->left = NULL;
    node->right = NULL;
    node->val = num;
    return node;
}

Tree *insertt(Tree *node, int num)
{
    if(node == NULL)
    {
        node = creat(num);
    }
    else
    {
        if(num < node->val) node->left = insertt(node->left, num);
        else if (num > node->val) node->right = insertt(node->right, num);
    }
    return node;
}

void preorder(Tree *posttree)
{
    if(posttree != NULL)
    {
        if(cnt==n-1) printf("%d\n", posttree->val);
        else
        {
            printf("%d ", posttree->val);
            cnt++;
        }
        preorder(posttree->left);
        preorder(posttree->right);
    }
}

void build(int *s, int len)
{
    root = NULL;
    cnt = 0;
    for(int i = 0; i < len; i++)
    {
        int num = s[i];
        root = insertt(root, num);
    }
}

int main()
{
   // freopen("in.txt", "r", stdin);
    int seq[N];
    while(~scanf("%d", &n))
    {
        for(int i = 0; i < n; i++)
            scanf("%d", &seq[i]);
        build(seq, n);
        preorder(root);
    }
}


猜你喜欢

转载自blog.csdn.net/Flynn_curry/article/details/60780553