c++二叉树通过先序中序确定后序

#include<cstdio>
#include<iostream>
#include<string>
using namespace std;


struct node
{
  char data;
  node * ln;
  node * rn;
  node(char c)
  :data(c)
  ,ln(NULL)
  ,rn(NULL){}
};

node *build(string str1,string str2)
{
  if(str1.size()==0)
  {
    return NULL;
  }
  char c=str1[0];
  node *root=new node(c);
  int position =str2.find(c);
  root->ln=build(str1.substr(1,position),str2.substr(0,position));
  root->rn=build(str1.substr(position+1),str2.substr(position+1));
  return root;
}

void postorder(node *root)
{
  if(root==NULL) return;
  postorder(root->ln);
  postorder(root->rn);
  printf("%c",root->data);
  return ;
}

int main()
{
 string str1,str2;
 while(cin>>str1>>str2)
 {
   node *root=build(str1,str2);
   postorder(root);
   printf("\n");
 }
  system("pause");
  return 0;
}
发布了22 篇原创文章 · 获赞 1 · 访问量 581

猜你喜欢

转载自blog.csdn.net/baidu_37143827/article/details/104594992
今日推荐