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.二叉搜索树(指针+前中后序遍历)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升
- 2024-05-08代码报错不用愁,CodeGeeX一键完成代码修复、错误解释的功能上线了!
- 2024-05-08今天开始程序员不用再发愁写commit message了,全部由CodeGeeX自动完成!