Acwing 3540.二叉搜索树(指针+前中后序遍历)

2022/8/4 23:27:24

本文主要是介绍Acwing 3540.二叉搜索树(指针+前中后序遍历),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

https://www.acwing.com/problem/content/description/3543/

输入一系列整数,利用所给数据建立一个二叉搜索树,并输出其前序、中序和后序遍历序列。

输入格式
第一行一个整数 n,表示输入整数数量。

第二行包含 n 个整数。

输出格式
共三行,第一行输出前序遍历序列,第二行输出中序遍历序列,第三行输出后序遍历序列。

输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。

数据范围
1≤n≤100,
输入元素取值范围 [1,1000]。

输入样例:
5
1 6 5 9 8
输出样例:
1 6 5 9 8
1 5 6 8 9
5 8 9 6 1
#include<bits/stdc++.h>
using namespace std;
int n;
typedef unsigned long long ULL;
typedef long long LL;
typedef long double LD;
typedef pair<int,int> PII;
typedef pair<string,int> PSI;
typedef struct node
{
    node *l,*r;//左右子树
    int val;//自己的权值
}*Node;
Node add(int x)
{
    Node tmp=new node;//建立新指针
    tmp->val=x;//初始化权值
    tmp->l=tmp->r=nullptr;//初始化左右子树
    return tmp;
}
Node insert(Node root,int x)//插入操作
{
    if(!root) return add(x);//在最底部的时候,直接新增节点
    if(x>root->val) root->r=insert(root->r,x);//如果大于根节点,就往右子树靠近
    else if(x<root->val) root->l=insert(root->l,x);//如果小于根节点,就往左子树靠近
    return root;
}
void pre(Node root)//前序遍历
{
    if(!root) return ;//到底了
    printf("%d ",root->val);//先输出根节点
    pre(root->l);//左子树
    pre(root->r);//右子树
}
void in(Node root)
{
    if(!root) return ;
    in(root->l);//左
    printf("%d ",root->val);//根
    in(root->r);//右
}
void post(Node root)
{
    if(!root) return ;
    post(root->l);
    post(root->r);
    printf("%d ",root->val);
}
int main()
{
    //cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    Node root=nullptr;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        root=insert(root,x);//沿着根节点插入
    }
    pre(root);//前序遍历
    cout<<endl;
    in(root);//中序遍历
    cout<<endl;
    post(root);//后序遍历
    cout<<endl;
    return 0;
}


这篇关于Acwing 3540.二叉搜索树(指针+前中后序遍历)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程