ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

二叉树遍历 A1102. Invert a Binary Tree (25) 反转二叉树 并输出层序和中序遍历 (使用静态二叉树)

2020-01-24 17:03:41  阅读:205  来源: 互联网

标签:Node Binary 遍历 int 二叉树 rchild now root lchild


 

 

#include <bits/stdc++.h>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
using namespace std;
const int maxn = 110;
struct node{
    int lchild,rchild;
}Node[maxn];
bool notRoot[maxn] = {false};//记录是否不是根节点,初始均是根节点
int n,num = 0;//n为节点个数,num为当前已经输出的节点个数
//print函数输出节点id的编号
void print(int id){
    printf("%d",id);
    num++;
    if(num < n)printf(" ");
    else printf("\n");
}
//中序遍历
void inOrder(int root){
    if(root == -1){
        return;
    }
    inOrder(Node[root].lchild);
    print(root);
    inOrder(Node[root].rchild);
}
//层序遍历
void BFS(int root){
    queue<int> q;
    q.push(root);
    while(!q.empty()){
        int now = q.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 postOrder(int root){
    if(root == -1){
        return;
    }
    postOrder(Node[root].lchild);
    postOrder(Node[root].rchild);
    swap(Node[root].lchild,Node[root].rchild);
}
int strToNum(char c){
    if(c == '-'){
        return -1;
    }
    else{
        notRoot[c-'0'] = true;
        return c- '0';//返回节点编号
    }
}
int findRoot(){
    for(int i =0;i<n;++i){
        if(notRoot[i] == false){
            return i;
        }
    }
}
int main(){
    char lchild,rchild;
    scanf("%d",&n);
    for(int i=0;i<n;++i){
        scanf("%*c%c %c",&lchild,&rchild);
        Node[i].lchild = strToNum(lchild);
        Node[i].rchild = strToNum(rchild);
    }
    int root = findRoot();
    postOrder(root);
    BFS(root);
    num = 0;
    inOrder(root);
    system("pause");
    return 0;
}

 

标签:Node,Binary,遍历,int,二叉树,rchild,now,root,lchild
来源: https://www.cnblogs.com/JasonPeng1/p/12232351.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有