c++二叉树-----先序建树和中序遍历

#表示空格
输入:abc##de#g##f###(先序)
输出:c b e g d f a (中序)

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

struct node
{
  char data;
  node *ln;
  node *rn;

  node(char a)
    :data(a),
    ln(NULL),
    rn(NULL){}

};

node *build(int & position,string str)
{
  char x=str[position++];
  if(x=='#')
  return NULL;
  node *root=new node(x);
  root ->ln=build(position,str);
  root->rn=build(position,str);
  return root;

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

int main()
{
  string str;
  while(cin>>str)
  {
    int position=0;
    node *root=build(position,str);
    inorder(root);
    printf("\n");
  }
  return 0;

  system("pause");
  return 0;
}
发布了22 篇原创文章 · 获赞 1 · 访问量 582

猜你喜欢

转载自blog.csdn.net/baidu_37143827/article/details/104593775