|反转树-后序_交换-普通遍历|1102 Invert a Binary Tree (25分)

//因为题目直接给出的节点编号的关系,因此用二叉树的静态写法
//如果输入的是数字,则直接把lchild或是rchild
//如果是“-”,则认为该侧没有孩子节点,记作-1

//同时还需要找到这棵树的根节点
//而这只需要找到一个节点,它不是任何节点的孩子即可(开1个bool型数组notRoot,在输入时进行记录)
// 8
// 1 -//0的左孩子是1,没有右孩子
// - -
// 0 -
// 2 7
// - -
// - -
// 5 -
// 4 6
#include <iostream>
#include <cstdio>
#include <algorithm>
//#include <cstdio>
using namespace std;

struct node{
    
    
    int lchild,rchild;
}Node[110];

bool isRoot[110]={
    
    true};//初始化,每个节点都是根节点

int strToNum(char c){
    
    
    if(c=='-')return -1;
    else{
    
    
        isRoot[c-'0']=false;//标记c不是根节点
        return c-'0';//返回节点编号
    }
}

//寻找根节点编号
int findRoot(){
    
    
    for(int i=0;i<n;i++){
    
    
        if(isRoot[i]==true) 
            return i;//i是根节点,返回i
    }
}

void postOrder(int root){
    
    
    if(root==-1)return;
    postOrder(Node[root].lchild);
    postOrder(Node[root].rchild);
    swap(Node[root].lchild,Node[root].rchild);//交换左右节点
}
int num=0;//num已经输出的节点个数
void print(int id){
    
    
    printf("%d",id);
    num++;
    if(num<n)printf(" ");
    else printf("\n");
}
void bfs(int root){
    
    
    queue<int> q;//注意队列里面放的是地址
    q.push(root);
    while(!q.empty()){
    
    
        int noe=w.front();
        q.pop();
        print(now);
        if(Node[now].lchild!=-1)q.push(Node[now].lchild);
        if(Node[now].rchild!=-1)q.push(Node[now].rchild);
    }
    
}
void inOrder(int root){
    
    
    if(root==-1)return;
    inOrder(Node[root].lchild);
    print(root);
    inOrder(Node[root].rchild);
}
int main()
{
    
    
    char lchild,rchild;//1 -
    scanf("%d",&n);//节点个数//8
    for(int i=0,i<n;i++){
    
    
        getchar();//吸收换行符
        scanf("%c %c",&lchild,&rchild);//左右孩子节点//1 -
        Node[i].lchild = strToNum(lchild);//char->int,顺便判断一下是不是根节点,就是它不是任何节点的孩子
        Node[i].rchild = strToNum(rchild);
    }
    int root = findRoot();//获得根节点编号
    postOrder(root);//后序遍历,反转二叉树
    bfs(root);
    inOrder(root);//中序遍历序列
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44769957/article/details/109037209