编程语言
首页 > 编程语言> > 树算法专题(一)二叉树的遍历

树算法专题(一)二叉树的遍历

作者:互联网

问题:知先中输后层

Sample Input

9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6

Sample Output

1 2 3 4 5 6 7 8 9
7 4 2 8 9 5 6 3 1

代码:

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdio>
#include<cstdlib>
using namespace std;

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

node* creat(int preL,int preR,int inL,int inR);
void layerOrder(node *root);
void PostOrder(node *root);

int pre[50],in[50],post[50];

int n;
int main(){
    while(cin>>n){
        for(int i=0;i<n;i++){
            cin>>pre[i];
        }
        for(int i=0;i<n;i++){
            cin>>in[i];
        }
        node* root = creat(0,n-1,0,n-1);
        layerOrder(root);//层次遍历
        cout<<endl;
        PostOrder(root);//后序遍历
        cout<<endl;
    }
    return 0;
}

node* creat(int preL,int preR,int inL,int inR){//建树
    if(preL>preR){
        return NULL;
    }
    node *root = (node*)malloc(sizeof(node));
    root->data = pre[preL];
    int k;
    for(k=inL;k<=inR;k++){
        if(pre[preL]==in[k]){
            break;
        }
    }
    int numLeft = k-inL;
    root->lchild=creat(preL+1,preL+numLeft,inL,k-1);
    root->rchild=creat(preL+numLeft+1,preR,k+1,inR);
    return root;
}

void layerOrder(node *root){
    queue<node*> p;
    p.push(root);
    while(!p.empty()){
        node* now = p.front();
        p.pop();
        printf("%d ",now->data);
        if(now->lchild != NULL){
            p.push(now->lchild);
        }
        if(now->rchild != NULL){
            p.push(now->rchild);
        }
    }
}

void PostOrder(node *root){
    if(root==NULL){
        return;
    }
    PostOrder(root->lchild);
    PostOrder(root->rchild);
    printf("%d ",root->data);
}

 

标签:node,preL,遍历,int,算法,二叉树,rchild,now,root
来源: https://www.cnblogs.com/bijian/p/12381779.html