重构二叉树(根据前序和中序)

来源:互联网 发布:春到人间草木知 编辑:程序博客网 时间:2024/05/21 13:21

题目来源:http://cie.xtu.edu.cn/exam/index.php/problem/exam_read/id/1046/exam_id/33

题目大意:给出一个二叉树的前序和中序遍历,重构二叉树,然后查找指定结点的孩子结点,参考了网上的算法。

// 重构二叉树.cpp : 定义控制台应用程序的入口点。#include "stdafx.h"#include "iostream"#include "stdlib.h"#include "stdio.h"#include "string.h"using namespace std;int i,j;struct BinaryNode{    char node;    BinaryNode *left;    BinaryNode *right;};BinaryNode *Repair(char *prestr,char *orderstr,int n){     BinaryNode *temp = new BinaryNode;     char *point;     int k = 0;     if(n<=0)         return NULL;     temp->node = prestr[0];     for(point = orderstr;point<orderstr+n;point++)//主要算法是找到中序中和前序中第一个元素相同的位置,然后把str2分割成两份。     {         if(*point == *prestr)              break;     }     k = point-orderstr;     temp->left = Repair(prestr+1,orderstr,k);//前序的第一个为根,故每次都从+1个元素开始递归     temp->right = Repair(prestr+k+1,point+1,n-k-1);//前序也按照point的位置分成两个部分     return temp;}void PrintNode(BinaryNode *T,char *str,char *result){if(T){if(T->node==str[i]){if(T->left)    result[j]=T->left->node;elseresult[j]='#';j++;if(T->right)   result[j]=T->right->node;elseresult[j]='#';i++;j++;}PrintNode(T->left,str,result);PrintNode(T->right,str,result);}}int main(){char orderstr[1000]={0},prestr[1000]={0};    int num;    cin>>num;    while(num--)    {        BinaryNode *Root;   int M,n;   char str[1000],result[1000]={0};        cin>>prestr;        cin>>orderstr;   cin>>M;   for(int k=0;k<M;k++)   cin>>str[k];        Root=Repair(prestr,orderstr,strlen(prestr));        PrintNode(Root,str,result);       for(n=0;n<2*(M-1);n=n+2)       cout<<result[n]<<result[n+1]<<" ";       cout<<result[n]<<result[n+1]<<endl;   i=0;j=0;    }}


原创粉丝点击