• 二叉树的遍历 及前中序转换成后序遍历


    给出一棵二叉树的中序和前序遍历,输出它的后序遍历。

    Input:

         本题有多组数据,输入处理到文件结束。
    
        每组数据的第一行包括一个整数n,表示这棵二叉树一共有n个节点。
    
        接下来的一行每行包括n个整数,表示这棵树的中序遍历。
    
        接下来的一行每行包括n个整数,表示这棵树的前序遍历。
    
        3<= n <= 100 

    Output:

    每组输出包括一行,表示这棵树的后序遍历。

    Sample Input:

    7
    4 2 5 1 6 3 7
    
    1 2 4 5 3 6 7 

    Sample Output:

    4 5 2 6 7 3 1 

    代码:

    #include<iostream>
    #include<stdio.h>
    #include<queue>
    #include<cstring>
    
    using namespace std;
    
    int Q[105];//存放前序遍历 
    int Z[105];//存放中序遍历
    
    struct TreeNode{  //树节点 
    	int data;
    	TreeNode *l,*r;
    };
    
    TreeNode * Tranlate (int fro,int mid,int len){   //把前序和中序遍历结果转换为二叉树 
    	if(len == 0)return NULL;
    	
    	TreeNode *node = new TreeNode;
    	node->data = Q[fro];
    	int tlen = 0;	
    	while(1){
    		if(Z[mid+tlen] == Q[fro])break;
    		++tlen;
    	}
    	node->l = Tranlate(fro+1,mid,tlen);
    	node->r = Tranlate(fro+tlen+1,mid+tlen+1,len - tlen - 1);
    	
    	return node;
    }
    void BackP(TreeNode const *head){   //进行后序遍历并输出 
    	if(head == NULL)return ;
    	
    	BackP(head->l);
    	BackP(head->r);
    	printf("%d ",head->data);//注意这里的输出格式,这里最后一个数后也有空格。(贼坑) 
    }
    
    int main(){
    	int N;
    	while(scanf("%d",&N)!=EOF){
    		for(int i=0 ; i<N ; i++)scanf("%d",&Z[i]);
    		for(int i=0 ; i<N ; i++)scanf("%d",&Q[i]);
    		TreeNode *head = Tranlate(0,0,7);
    		BackP(head);
    		printf("
    ");
    	}
    	return 0;
    }
  • 相关阅读:
    hbase与Hive的集成
    HBase API操作
    HBase原理
    HBase数据结构
    HBase Shell操作
    HBase简介
    Boxes in a Line
    B
    B. Painting Pebbles
    X
  • 原文地址:https://www.cnblogs.com/vocaloid01/p/9514315.html
Copyright © 2020-2023  润新知