排序二叉树 构建与遍历 cs精英挑战营 习题

在这里插入图片描述

#include<stdio.h>
#include<iostream>
#include<vector>
using namespace std;
const int N = 100001;
// 排序二叉树,左小右大


struct node{
    int val,l,r;
}t[N];
//利用结构体数组来形成二叉树的数据结构

/*java 语言写法
class node{
    public int val;
    public int l;
    public int r;
}

node[] t = new node[N];

python写法
class node:
    val = int(),
    l = int(),
    r = int()
 */

int root,c; //root整个二叉树的根节点,c为整个二叉树的大小

//在树中插入一个数字
//v为要插入的数字 x为当前节点的下标 返回根节点x
int insert(int v,int x){
    if(x == 0){ //根节点不存在时将x变为根节点,c++默认数组的初始化全为0
        x = ++c; 
        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:存储结果的数组

//dlr前序遍历  根左右
void dlr(int x, vector<int> &ans){
    if(x){  //注意java中不能直接写if(x) 因为java中int不能强转到bool 
        //加入x节点的val到ans中,递归求解左右子树
        ans.push_back(t[x].val); // java .add()和python .append()
        dlr(t[x].l,ans);
        dlr(t[x].r,ans);
    }
}

//lrd后序遍历  左右根
void lrd(int x, vector<int> &ans){
    if(x){
        //递归求解左右子树,加入x的节点的val到ans中
        lrd(t[x].l,ans);
        lrd(t[x].r,ans);
        ans.push_back(t[x].val);
    }
}

// java python 的list 与 c++的vector 对应
vector<int> getAnswer(int n, vector<int> seqence){
    root = c = 0;  //初始化
    for(int i=0; i<int(seqence.size());++i)
        root = insert(seqence[i],root);
    vector<int> ans;
    dlr(root,ans);
    lrd(root,ans);
    return ans;
}

int main(){
    int n,x;
    scanf("%d",&n);
    vector<int> seqence;
    for(int i = 0; i < n; ++i){
        scanf("%d",&x);
        seqence.push_back(x);
    }
    vector<int> ans = getAnswer(n, seqence);
    for(int i=0; i<n; i++){
        cout<<ans[i]<<" ";
    }
    cout<<endl;
    for(int i=n; i<2*n; i++){
        cout<<ans[i]<<" ";
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值