PAT1102用笨办法解翻转二叉树

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
struct node{
    int id,l,r;
}a[100];
int root = 0;
bool flag = false;
void inorder(int v1)
{
    if(v1 == -1)
        return ;
    inorder(a[v1].r);
    if(flag == true)
    {
        printf("%d",a[v1].id);
        flag = false;
    }
    else
        printf(" %d",a[v1].id);
    inorder(a[v1].l);

}
int main(){
    int n,have[100] = {0};
    cin >> n;
    for(int i = 0;i<n;i++)
    {
        a[i].id = i;
        string l,r;
        cin >> l>>r;
        if(l != "-")
        {
            a[i].l = stoi(l);
            have[stoi(l)] = 1;//代表这个节点是子节点;
        }
        else{
            a[i].l = -1;
        }
        if(r != "-")
        {
            a[i].r = stoi(r);
            have[stoi(r)] = 1;//代表这个节点是子节点;
        }
        else{
            a[i].r = -1;
        }
     }
     while(have[root] == 1) root++; //通过它找到根
     queue<int> q;
     q.push(root);
     while(!q.empty())
     {
         int temp = q.front();
         if(temp == root)
            printf("%d",a[temp].id);
         else
            printf(" %d",a[temp].id);
         q.pop();
         if(a[temp].r != -1)
         {
             q.push(a[temp].r);
         }
         if(a[temp].l != -1)
         {
             q.push(a[temp].l);
         }

     }
     printf("\n");
     flag = true;
     inorder(root);
     return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值