甲1102. Invert a Binary Tree (25)

#include <cstdio>
#include <cstdlib>
#include <string.h>
#include <cmath>
#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
using namespace std;

struct node
{
    int data;
    node* lchild;
    node* rchild;
};

bool harsh[11]={false};

int a[11][2];
int N;

node* create(int x)
{
    if(x==-1)
    {
        return NULL;
    }
    node* root=new node;
    root->data=x;
    root->lchild=create(a[x][0]);
    root->rchild=create(a[x][1]);
    return root;
}

void levelorder(node* &root)
{
    if(root->data==-1)
    {
        return;
    }
    queue<node*> q;
    q.push(root);
    int c=0;
    while(!q.empty())
    {
        node* top=q.front();
        q.pop();
        printf("%d",top->data);
        c++;
        if(c!=N)
        {
            printf(" ");
        }
        if(top->rchild!=NULL)q.push(top->rchild);
        if(top->lchild!=NULL)q.push(top->lchild);
    }
    printf("\n");
}


int num=0;
void inorder(node* &root)
{
    if(root==NULL)
        return;
    inorder(root->rchild);
    printf("%d",root->data);
    num++;
    if(num!=N)printf(" ");
    else printf("\n");
    inorder(root->lchild);
}

int main()  
{   

    scanf("%d",&N);
    getchar();
    for(int i=0;i<N;i++)
    {
        char c;
        c=getchar();
        if(c>='0'&&c<='9')
        {
            a[i][0]=c-'0';
            harsh[a[i][0]]=true;
        }
        else
        {
            a[i][0]=-1;
        }
        getchar();
        c=getchar();
        if(c>='0'&&c<='9')
        {
            a[i][1]=c-'0';
            harsh[a[i][1]]=true;
        }
        else
        {
            a[i][1]=-1;
        }
        getchar();
    }
    int k;
    for(int i=0;i<N;i++)
    {
        if(harsh[i]==false)
        {
            k=i;
            break;
        }
    }
    node* root =create(k);
    levelorder(root);
    inorder(root);
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yhy489275918/article/details/80138004
今日推荐