UVA679 / UVA122 学习二叉树

详细内容翻阅紫书p148~p155





#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
#include <map>
using namespace std;
int d,I;
const int maxn = 1048586;
int main(){
    int i,t,k;
    scanf("%d",&t);
    while (t--) {
        scanf("%d%d",&d,&I);
        k = 1;
        for(i=1;i<d;i++){
            if(I%2){
                k *= 2;
                I = I/2+1;
            }else{
                k = k*2+1;
                I = I/2;
            }
        }
        printf("%d\n",k);
    }
    return 0;
}





#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
#include <map>
using namespace std;
struct node{
    bool have_value;
    int value;
    node *left,*right;
    node(): have_value(false),left(NULL),right(NULL){};
}*root;
node *newNode(){
    return new node();
}
char in[110];
bool inputError;
vector<int> ans;
void removeTree(node *u){
    if(u==NULL){
        return;
    }
    removeTree(u->left);
    removeTree(u->right);
    delete u;
}
void addNode(int val,char *s){
    int len = strlen(s);
    node *now = root;
    int i;
    for(i=0;i<len-1;i++){
        if(s[i]=='L'){
            if(now->left==NULL){
                now->left = newNode();
            }
            now = now->left;
        }else{
            if(now->right==NULL){
                now->right = newNode();
            }
            now = now->right;
        }
    }
    if(now->have_value){
        inputError = true;
    }
    now->value = val;
    now->have_value = true;
}
bool bfs(){
    queue<node*> que;
    ans.clear();
    que.push(root);
    while(que.size()){
        node *q = que.front();
        que.pop();
        if(!q->have_value){
            return false;
        }
        ans.push_back(q->value);
        if(q->left!=NULL){
            que.push(q->left);
        }
        if(q->right!=NULL){
            que.push(q->right);
        }
    }
    return true;
}
void clear(){
    removeTree(root);
    root = newNode();
    inputError = false;
}
int main(){
    int i,j,v;
    clear();
    while(~scanf("%s",in)){
        if(!strcmp(in, "()")){
            if(bfs()&&!inputError){
                int size = ans.size();
                for(i=0;i<size;i++){
                    printf("%d%c",ans[i],i==size-1?'\n':' ');
                }
            }else{
                printf("not complete\n");
            }
            
            clear();
            continue;
        }
        sscanf(in+1, "%d", &v);
        addNode(v, strchr(in, ',')+1);
    }
    return 0;
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值