先序遍历:输出自己 -> 左子树 ->右子树
中序遍历:输出左子树 -> 自己 ->右子树
#include <bits/stdC++.h>
using namespace std;
struct node
{
//val 根节点
//lch 左子树
//rch 右子树
int val,lch,rch;
} t[10000];
//root代表根节点
//cnt代表二叉树大小
int root,cnt;
//建树
int insert(int v,int x)
{
if(x == 0)
{
x = ++cnt;
t[x].val = v;
t[x].lch = 0;
t[x].rch = 0;
// printf("x = %d val = %d\n",x,t[x].val);
return x;
}
/*t[x].lch && t[x].rch 实际是子树的x不记录数值起引导作用
t[x].val 是记录值*/
if(t[x].val > v)
t[x].lch = insert(v,t[x].lch);
else
t[x].rch = insert(v,t[x].rch);
printf("\nx = %d | val = %d | lch = %d | rch = %d",x,t[x].val,t[x].lch,t[x].rch);
printf("\n V\n");
return x;
}
// 先序遍历
void dlr(int x,vector<int> &ans)
{
if(x)
{
ans.push_back(t[x].val);
dlr(t[x].lch,ans);
dlr(t[x].rch,ans);
}
}
vector<int> getAnswer(int n, vector<int> sequence)
{
root = cnt = 0;//初始根节点从0开始
for(int i = 0;i < sequence.size();i++)
root = insert(sequence[i],root);
vector<int> ans;
dlr(root,ans);
return ans;
}
int main()
{
int n;
scanf("%d", &n);
vector<int> sequence;//定义向量
for (int i = 0; i < n; ++i)
{
int x;
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]);
return 0;
}