PAT 1102. Invert a Binary Tree (25)

层次遍历先输出右节点

(原来以为是先输出大的 提交以后有一个错误 测试点1 仔细看过代码后发现没错误就觉得是这个问题 一试就成功)

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
#define maxsize 100001
#define  min(a,b) a<b?a:b
struct  tree{
char left;
char right;
}a[10];
int first=0;
void Swap(char *a,char *b)
{
    char t=*a;
    *a=*b;
    *b=t;
}
void levelorder(int root,tree a[])
{
    queue<int> q;
    q.push(root);
    int t;
    while(!q.empty())
    {
        t=q.front();
        if(t==root)
        printf("%d",t);
        else
            printf(" %d",t);
        q.pop();
        if(a[t].left!='-'&&a[t].right!='-')
         {
                    q.push(a[t].right-'0');
                     q.push(a[t].left-'0');
         }
         else if(a[t].left!='-'&&a[t].right=='-')
           q.push(a[t].left-'0');
        else  if(a[t].left=='-'&&a[t].right!='-')
                    q.push(a[t].right-'0');
                    if(a[t].left!=a[t].right)
                Swap(&a[t].left,&a[t].right);//直接在层次遍历中实现调换
    }
    printf("\n");
}
void inorder(tree a[],int index)
{
    if(a[index].left!='-')
    inorder(a,a[index].left-'0');
    if(!first)
    {
     printf("%d",index);
        first++;
    }
    else
        printf(" %d",index);
        if(a[index].right!='-')
    inorder(a,a[index].right-'0');
}
int main()
{
   int n;
   int b[10]={0};
   scanf("%d",&n);

   for(int i=0;i<n;i++)
   {getchar();
   scanf("%c %c",&a[i].left,&a[i].right);
   if(a[i].left!='-')
    b[a[i].left-'0']=1;
   if(a[i].right!='-')
    b[a[i].right-'0']=1;
   }
   int root;
   for(int i=0;i<n;i++)
    if(!b[i])
    {
        root=i;
        break;
    }

   levelorder(root,a);

 inorder(a,root);








    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值