ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-08-04 20:02:08  阅读:161  来源: 互联网

标签:Node typedef 遍历 3540 val 前中 return root Acwing


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;
}

标签:Node,typedef,遍历,3540,val,前中,return,root,Acwing
来源: https://www.cnblogs.com/Vivian-0918/p/16552190.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有