题意:给你一个整数序列,按照这个序列构造一颗二叉排序树

输出一个整数序列,要求按照这个序列构造的二叉排序树的形状和原来的一样,而且序列的字典序最小

做法:按照题目的序列构造好二叉排序树后直接按照先根遍历的顺序输出即可,因为左儿子小于右儿子,所以在根先输出的情况下,尽量都先输出左儿子,刚好符合先根遍历的特点

从来不写指针,最近也偶尔写写,尝试不同的方法

View Code
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node{
    int num;
    struct node *left;
    struct node *right;
}*tree;
int tot=0;
node *build(node *root,int num)
{
    if(root==NULL)
    {
        root=new node;
        root->left=NULL;
        root->right=NULL;
        root->num=num;
        return root;
    }
    else 
    {
        int t=root->num-num;;
        if(t>0)
            root->left=build(root->left,num);
        else 
            root->right=build(root->right,num);
        return root;
    }
}
bool first;
void visit(node *root)
{
    if(root!=NULL&&!first)
         printf(" %d",root->num);
    else 
    {
        first=false;
        printf("%d",root->num);
    }
}
void preorder(node *root)
{
    if(root!=NULL)
    {  
        visit(root);
        preorder(root->left);
        preorder(root->right);
    }
}
int main()
{
    int n,num;
    while(scanf("%d",&n)!=EOF)
    {
        first=true;
        int num;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&num);
            tree=build(tree,num);
        }
        preorder(tree);
        puts("");
    }
    return 0;
}

相关文章:

  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
  • 2021-06-05
  • 2022-12-23
  • 2021-12-17
  • 2021-10-13
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-03-02
  • 2021-10-26
  • 2021-05-23
相关资源
相似解决方案