时间限制:2s,空间256MB
问题描述
给定一个1到n的排列(无重复元素),按顺序依次插入到一棵二叉排序树中,请你将这棵二叉树前序遍历和后序遍历输出。
保证树高不超过50 。
输入
第一行一个整数n。(1 ≤ n ≤ 100000)
接下来一行表示为n个整数,代表1到n的一个排列。
输出
输出所建成的二叉树的前序遍历和后序遍历
输入样例
10
2 6 9 3 5 7 10 8 4 1
输出样例
2 1 6 3 5 4 9 7 8 10
1 4 5 3 8 7 10 9 6 2
测试输入
20
8 6 4 13 15 17 11 12 19 18 16 10 7 1 2 7 3 5 9 14
测试输出
8 6 4 1 2 3 5 7 7 13 11 10 9 12 15 14 17 16 19 18
3 2 1 5 4 7 7 6 9 10 12 11 14 16 18 19 17 15 13 8
二叉排序树
左子树小于节点,右子树大于节点
include<vector>
include<iostream>
using namespace std;
const int N =100005;
struct node{
int val,l,r;
}t[N];
int root,cnt;//root整个二叉树的根节点,cnt整个二叉树的大小
//在以x为根的树中插入一个数字v
//v:要插入的数字
//x:当前节点,下标
//返回根节点x
int insert(int v, intx){
if(x==0){
//根节点还不存在,则将x变成根节点
//或如果该节点不存在,即左孩子不存在x=t[x].l=0或右孩子不存在x=t[x].r=0,则将v插入当前节点
x=++cnt;
t[x].val=v;
t[x].l=0;
t[x].r=0;
return x;
}
//递归插入左右子树,先与根节点比较
if(t[x].val<v)
t[x].r = insert(v,t[x].r);
else
t[x].l = insert(v,t[x],l);
return x;
}
//以x为根的二叉树的前序遍历
//x:当前节点
//ans:存储结果的数组
void dlr(int x,vector<int> &ans){
if(x){
//加入x节点的val的ans中,递归求解左右子树
ans.push_back(t[x].val);
dlr(t[x].l,ans);
dlr(t[x].r,ans);
}
}
//后序遍历
void lrd(int x,vector<int> &ans){
if(x){
lrd(t[x].l,ans);
lrd(t[x].r,ans);
ans.push_back(t[x].cal);
}
}
//给定一个1到n的排列,依次插入到二叉树中,返回前序遍历和后序遍历
//n:如题意
//sequence:给定的排列,大小为n
//返回值:将要输出的元素依次加入到返回值中
vector<int> getAnswer(int n ,vector<int> sequence){
root = cnt =0;
for(int i=0; i< int(sequence.size());++i)
root = insert(squence[i],root);
vector<int> ans;
dlr(root,ans);
lrd(root,ans);
return ans;
}
int main(){
int n,x;
scanf("%d",&n);
vector<int> sequence;
for(int i=0; i<n;++i){
scanf("%d",&x);
sequence.push_back(x);
}
vector<int>ans = getAnswer(n,sequence);
for (int i=0;i<n;++i)
printf("%d%c",ans[i]," \n"[i==n-1]);
for(int i=0; i<n;++i)
printf("%d%c",ans[n+i]," \n"[i==n-1]);
return 0;
}