邓俊辉 算法训练营练习 - 二叉排序树

先序遍历:输出自己 -> 左子树 ->右子树
中序遍历:输出左子树 -> 自己 ->右子树 

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

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值