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

排序二叉树 构建与遍历 cs精英挑战营 习题_第1张图片

#include
#include
#include
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 &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 &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 getAnswer(int n, vector seqence){
    root = c = 0;  //初始化
    for(int i=0; i ans;
    dlr(root,ans);
    lrd(root,ans);
    return ans;
}

int main(){
    int n,x;
    scanf("%d",&n);
    vector seqence;
    for(int i = 0; i < n; ++i){
        scanf("%d",&x);
        seqence.push_back(x);
    }
    vector ans = getAnswer(n, seqence);
    for(int i=0; i

你可能感兴趣的:(CS精英挑战营,算法,二叉树)