二叉树练习(知先序中序求层次)

 

 

写了一些题发现自己二叉树还有点弱

先是建树 没什么特别 就是 边界条件注意一下

node *build(node *root,int left,int right){
    root = new node();
    int t = a[cnt++];
    root -> index = t;
    int i;
    for(i = left;i < right;i++){
        if(t == b[i])
            break;
    }
    if(i > left && i < right){ /* 当中序排序中该元素不是 最左边 且满足是树 有左孩子*/
        root -> left = build(root -> left,left,i);
        /*** 一个根结点在中序排序 左边有元素时 有左孩子***/
    }
    if(i >= left && i < right -1){/* 同理 */
        root -> right = build(root -> right,i+1,right);
        /*** 一个根结点在中序排序中 右边有元素时 有右孩子***/
    }
    return root;
}

然后就是层次遍历 我用了个队列把每个节点的左右节点存在后面再pop出当前节点

void cengci(node *root){
    queue<node *> p;
    p.push(root); //加入根结点
    while(!p.empty()){
        cout<<p.front() -> index<<" ";
        if(p.front() -> left != NULL){//左节点不空就加入
            p.push(p.front()->left);
        }
        if(p.front() -> right != NULL){//同理
            p.push(p.front() -> right);
        }
        p.pop();
    }
}

完整的代码

#include<bits/stdc++.h>

using namespace std;
struct node{
    int index;
    node *left,*right;
    node(){
        left = NULL;
        right = NULL;
    }
};
int a[30];
int b[30];
int cnt = 0;
node *build(node *root,int left,int right){
    root = new node();
    int t = a[cnt++];
    root -> index = t;
    int i;
    for(i = left;i < right;i++){
        if(t == b[i])
            break;
    }
    if(i > left && i < right){ /* 当中序排序中该元素不是 最左边 且满足是树 有左孩子*/
        root -> left = build(root -> left,left,i);
        /*** 一个根结点在中序排序 左边有元素时 有左孩子***/
    }
    if(i >= left && i < right -1){/* 同理 */
        root -> right = build(root -> right,i+1,right);
        /*** 一个根结点在中序排序中 右边有元素时 有右孩子***/
    }
    return root;
}
void cengci(node *root){
    queue<node *> p;
    p.push(root); //加入根结点
    while(!p.empty()){
        cout<<p.front() -> index<<" ";
        if(p.front() -> left != NULL){//左节点不空就加入
            p.push(p.front()->left);
        }
        if(p.front() -> right != NULL){//同理
            p.push(p.front() -> right);
        }
        p.pop();
    }
}
int main(){
    node *root;
    int n;
    cin>>n;
    for(int i = 0;i < n;i++){
        cin>>a[i];
    }
    for(int i = 0;i < n;i++){
        cin>>b[i];
    }
    root = build(root,0,n);
    cengci(root);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值